Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - Rotating around a point, object consistently getting further

I'm making a game in Unity, and need an enemy to rotate around a point. I'm using atan2 to get the direction to the point, adding 90 degrees and then using cos and sin to change the position. After finding the object does rotate, but get further from the point, I decided to try this out in p5js. However I get the same issue.
Here is the code:

let x = 100;
let y = 100;
let speed = 5

function setup() {
  createCanvas(400, 400);
  angleMode(DEGREES)
}

function draw() {
  background(220);
  let dir = atan2(y - height / 2, x - width / 2);
  x += cos(dir + 90) * speed;
  y += sin(dir + 90) * speed;
  rect(x, y, 20, 20);
  console.log(dir)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>
question from:https://stackoverflow.com/questions/65866521/rotating-around-a-point-object-consistently-getting-further

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[...] but get further from the point [...]

Of course. You don't move on a circle. You move along the tangent of the circle. Each step on the tangent increases the distance from the center of the circle. Hence the distance to the center increase in each frame.

You can easily check this by scaling the distance vector with the ratio of the original distance and the current distance:

let x = 100;
let y = 100;
let speed = 5
let dist;

function setup() {
    createCanvas(400, 400);
    angleMode(DEGREES)
    dist = sqrt(pow(y - height/2, 2) + pow(x - width/2, 2));
}

function draw() {
    background(220);
    let dir = atan2(y - height / 2, x - width / 2);
    x += cos(dir + 90) * speed;
    y += sin(dir + 90) * speed;
    
    let newDist = sqrt(pow(y - height/2, 2) + pow(x - width/2, 2));
    x = (x - width/2) * dist/newDist + width/2
    y = (y - height/2) * dist/newDist + height/2
    
    rect(x, y, 20, 20);
    console.log(dir)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...