好的,我有一个大小为512x512
的游戏场地,它是循环的,-32
会变成x
和y
的512
。
现在我需要计算两个实体之间的角度,我有以下代码作为一种解决方法,它大部分时间都有效,但有时仍然失败:
Shooter.getAngle = function(a, b) {
var ax = a.x;
var bx = b.x;
if (a.x < this.width / 4 && b.x > this.width - this.width / 4) {
ax += this.width;
} else if (a.x > this.width - this.width / 4 && b.x < this.width / 4) {
bx += this.width;
}
var ay = a.y;
var by = b.y;
if (a.y < this.height / 4 && b.x > this.height - this.height / 4) {
ay += this.height;
} else if (a.y > this.height - this.height / 4 && b.y < this.height / 4) {
by += this.height;
}
return this.wrapAngle(Math.atan2(ax - bx, ay - by) + Math.PI);
};
我只是想不出如何正确地将
a
投影到b
上,以便正确考虑包装。如果有人能帮忙,那就太好了,因为远离目标的寻踪导弹并不好玩。
澄清一下,如果玩家向右移动,则导弹应跟随他越过场地边缘到达左侧,就像另一个玩家一样。
编辑:
这是一个测试版本,示例表明它正确地包装,但在不必包装的情况下会出现错误:
function getAngle(a, b) {
var tx = a.x - b.x;
var ty = a.y - b.y;
// actual area goes from -16 to 512 due to the border space that's out of screen
tx = ((tx + 16) % (480 + 32)) - 16;
ty = ((ty + 16) % (480 + 32)) - 16;
var r = Math.atan2(ty, tx) * (180 / Math.PI);
// example
// |> b a >|
// a.x = 460
// b.x = 60
// missile should go over the right border
// tx = 400
// r = 0
// missile goes right, OK
// example2
// |< a b <|
// a.x = 60
// b.x = 460
// missile should go over the left border
// tx = -400
// r = 180
// missile goes left, OK
// example3
// | a >>>> b |
// a.x = 60
// b.x = 280
// missile should go right
// tx = -220
// r = 180
// missile goes left, WRONG
// example4
// | b <<<< a |
// a.x = 280
// b.x = 60
// missile should go left
// tx = 220
// r = 0
// missile goes right, WRONG
console.log(ty, tx);
console.log(r);
}
function Point(x, y) {
this.x = x;
this.y = y;
}
getAngle(new Point(460, 240), new Point(60, 240));
getAngle(new Point(60, 240), new Point(460, 240));
getAngle(new Point(60, 240), new Point(280, 240));
getAngle(new Point(280, 240), new Point(60, 240));
看起来唯一让它工作的方法是检查 a.x < width * 0.25
和 b.x > width * 0.75
等情况,但这有缺陷,至少在我上面发布的版本中是如此:/
while()
代码在某些时候无法正常工作,尽管取模部分在之后加上了一些附加检查,但仍然存在问题。不管怎样,你的新包装代码运行得非常好。 - Ivo Wetzel