围绕一个点旋转,物体不断地走得更远

问题描述

我正在 Unity 中制作游戏,需要一个敌人围绕一个点旋转。我正在使用 atan2 获得指向该点的方向,添加 90 度,然后使用 cos 和 sin 来改变位置。在发现对象确实旋转后,但离题更远了,我决定在 p5js 中尝试一下。但是我遇到了同样的问题。
代码如下:

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>

解决方法

[...] 但离点更远 [...]

当然。你不会在一个圆圈上移动。你沿着圆的切线移动。切线上的每一步都会增加到圆心的距离。因此,每帧到中心的距离都会增加。

您可以通过使用原始距离和当前距离的比率缩放距离向量来轻松检查这一点:

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));
    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>