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?