围绕一个点旋转,物体不断地走得更远
Rotating around a point, object consistently getting further
我正在 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>
[...] but get further from the point [...]
当然可以。你不会在一个圆圈上移动。你沿着圆的切线移动。切线上的每一步都会增加到圆心的距离。因此每帧到中心的距离都会增加。
您可以通过使用原始距离与当前距离的比率缩放距离向量来轻松检查这一点:
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>
我正在 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>
[...] but get further from the point [...]
当然可以。你不会在一个圆圈上移动。你沿着圆的切线移动。切线上的每一步都会增加到圆心的距离。因此每帧到中心的距离都会增加。
您可以通过使用原始距离与当前距离的比率缩放距离向量来轻松检查这一点:
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>