Get Off My Lawn Get Off My Lawn - 2 months ago 12
Javascript Question

Move object based on its angle

I am trying moving an object based on its rotation, and I have 4 methods:


  • forward

  • backward

  • up

  • down



Of the 4 methods, only
forward
and
backward
seem to be working properly. 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.

Rotation Image

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

Answer

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).

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. Just -cos, for example, just means "move in the opposite direction in the x axis and keep the y axis velocity the same". The case where forward points North-Northeast, for example, would create a vector going North-Northwest.