我正在做一个统一的游戏,需要一个敌人围绕一个点旋转。我用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>
发布于 2021-01-24 00:36:28
...但离重点远点..。
当然了。你不能在一个圆圈上移动。你沿着圆圈的切线移动。切线上的每一步都会增加离圆心的距离。因此,在每一帧中,到中心的距离都会增加。
您可以很容易地通过缩放初始距离与当前距离之比的距离向量来检查这一点:
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>
https://stackoverflow.com/questions/65866521
复制相似问题