How to translate velocity vector to the gameobject local coordinates

TLDR: Need to know the x and y coordinates of the velocity vector on a gameobject that is going to be rotated

Long story:
I’m making a space game with pseudo realistic movement. That means there is no air friction and the ship continues moving at its speed unless you use the thrusters. Esentially you have the main thruster, a retro-thruster to brake and rotation thrusters.
Controlling such a ship is quite hard, so I wanted to provide a control to fire up automatic stop system that detects you velocity and activates the proper thrusters to reduce velocity.
This is what I have so far:

thrustStop() {
            var angle = this.angle * Math.PI / 180 ;
            var v = this.body.speed;
            var vx = this.body.velocity.x;
            var vy = this.body.velocity.y;

            var localVelocity = new Phaser.Math.Vector2(
                vx * Math.cos(angle) - vy * Math.sin(angle),
                vx * Math.sin(angle) + vy * Math.cos(angle)
            ); 

            if (Math.abs(localVelocity.x) > 0.01) {
                if (localVelocity.x < 0){
                    this.thrustRight();
                } else {
                    this.thrustLeft();
                }
            }

            if (Math.abs(localVelocity.y) > 0.01) {
                if (localVelocity.y < 0) {
                    this.thrustBackwards();
                } else {
                    this.thrustForward();
                }
            } 
        }

The localVelocity variable is supposed to be what I need but I guess my math is not so good, because its only working when moving up and the ship has not rotated at all. In any other situation the ship accelerates in crazy directions.

Any ideas?

Ok, I’m an idiot :stuck_out_tongue_winking_eye:

Math was almost right, just the angle sign was wrong:
So where it says
var angle = this.angle * Math.PI / 180;
should say
var angle = -this.angle * Math.PI / 180;

EDIT: Ups! And even better, it turns out that phaser-matter has a function for this, so the

var v = this.body.speed;
var vx = this.body.velocity.x;
var vy = this.body.velocity.y;
var localVelocity = new Phaser.Math.Vector2(
    vx * Math.cos(angle) - vy * Math.sin(angle),
    vx * Math.sin(angle) + vy * Math.cos(angle)
); 

can be substituted by:

var localVelocity = this.scene.matter.vector.rotate(this.body.velocity,angle);

Now I feel like a looser. Spent the whole afternoon working on that transformation for nothing :laughing:

2 Likes