matidfk
matidfk

Reputation: 35

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>

Upvotes: 1

Views: 122

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

[...] 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>

Upvotes: 1

Related Questions