[…]但要更进一步[…]
当然。你不能绕着圈子走。沿着圆的切线移动。切线上的每一步都会增加距圆心的距离。因此,在每一帧中,到中心的距离都会增加。
您可以通过使用原始距离和当前距离的比率缩放距离矢量来轻松检查这一点:
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>