简体   繁体   English

根据对象的角度移动对象

[英]Move object based on its angle

I am trying moving an object based on its rotation, and I have 4 methods: 我正在尝试根据对象的旋转来移动对象,并且我有4种方法:

  • forward 向前
  • backward 向后
  • up
  • down

Of the 4 methods, only forward and backward seem to be working properly. 在这4种方法中,只有forwardbackward才能正常工作。 The other two seem to have a different effect based on the rotation. 根据轮换,其他两个似乎有不同的效果。 When it is set to a 90 degree rotation it acts the same as forward (forward is down the screen at this rotation), but in reality the desired affect is for it to move right. 将其设置为90度旋转时,其作用与forward相同(在此旋转时,向前位于屏幕下方),但实际上,期望的效果是使其向右移动。

旋转影像

These two methods seem to be working properly: 这两种方法似乎正常工作:

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))
    );
}

These two however are not working properly. 但是,这两个不能正常工作。 I can not seem to figure out what is causing this, I assumed the math would be similar, maybe I am wrong on that? 我似乎无法弄清楚是什么原因造成的,我认为数学将是相似的,也许我错了吗?

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))
    );
}

You should calculate it this way: up is +90 degrees from forward , down is -90 degrees from forward (and backward is just 180 degrees from forward ). 您应该计算的话是这样的: up为+90度forwarddown为-90度forward (和backward仅仅是180度forward )。

In other words: 换一种说法:

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

Negating cos / sin without the other clearly isn't correct. 在没有对方的情况下否定cos / sin显然是不正确的。 Just -cos , for example, just means "move in the opposite direction in the x axis and keep the y axis velocity the same". 例如,Just -cos仅表示“在x轴上以相反的方向移动,并保持y轴速度相同”。 The case where forward points North-Northeast, for example, would create a vector going North-Northwest. 例如,如果forward点是东北-东北,则会创建一个沿着西北-西北移动的矢量。

If you calculate cos and sin for main direction once, then vector components are: 如果一次计算主方向的cos和sin,则向量分量为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM