Get Off My Lawn - 4 months ago 26

Javascript Question

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`

`backward`

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

);

}

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.