如何解决围绕一个点旋转,物体不断地走得更远
我正在 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。