根据角度

时间:2016-10-08 00:21:28

标签: javascript math typescript

我正在尝试根据旋转移动对象,我有4种方法:

  • 向前
  • 后向
  • 向下

在4种方法中,只有forwardbackward似乎正常工作。其他两个似乎根据旋转有不同的效果。当它设置为90度旋转时,它的作用与forward相同(在此旋转时向前移动到屏幕下方),但实际上所需的效果是它向右移动。

Rotation Image

这两种方法似乎运作正常:

public get forward(): Vector2 {
    return new Vector2(
        Math.cos(this.rotation.degrees * (Math.PI / 180)),
        Math.sin(this.rotation.degrees * (Math.PI / 180))
    );
}

public get backward(): Vector2 {
    return new Vector2(
        -Math.cos(this.rotation.degrees * (Math.PI / 180)),
        -Math.sin(this.rotation.degrees * (Math.PI / 180))
    );
}

然而这两个工作不正常。我似乎无法弄清楚造成这种情况的原因,我认为数学会相似,也许我错了?

public get up(): Vector2 {
    return new Vector2(
        Math.cos(this.rotation.degrees * (Math.PI / 180)),
        -Math.sin(this.rotation.degrees * (Math.PI / 180))
    );
}

public get down(): Vector2 {
    return new Vector2(
        -Math.cos(this.rotation.degrees * (Math.PI / 180)),
        Math.sin(this.rotation.degrees * (Math.PI / 180))
    );
}

2 个答案:

答案 0 :(得分:1)

你应该这样计算:upforward相距+ 90度,downforward相距-90度(而backward只是距离forward)180度。

换句话说:

public get up(): Vector2 {
    const phi = (this.rotation.degrees + 90) * (Math.PI / 180);
    return new Vector2(
        Math.cos(phi),
        Math.sin(phi)
    );
}

否定cos / sin而另一方显然不正确。例如,仅-cos表示"在x轴上沿相反方向移动并保持y轴速度相同"。例如,forward指向北东北的情况会产生一个向西北偏北的矢量。

答案 1 :(得分:1)

如果计算主方向的cos和sin一次,则矢量分量为:

forward:            cos,   sin
backward:          -cos,   -sin
up(really left):   -sin,    cos
down(really right): sin,   -cos