I've been playing around with trying to create some kind of top down racer but I'm having trouble getting the car to turn properly. At the moment this is the code I have to update the position of the car:
var power;
if (keyboard.upKeyDown) {
power = 1;
} else {
power = 0;
}
if (keyboard.leftKeyDown) {
this.rotate -= 0.05;
} else if (this.keyboard.rightKeyDown) {
this.rotate+= 0.05;
}
this.velocityX += Math.cos(this.rotate) * power;
this.velocityY += Math.sin(this.rotate) * power;
var cDrag = 0.98;
this.velocityX *= cDrag;
this.velocityY *= cDrag;
this.positionX += this.velocityX;
this.positionY += this.velocityY;
At the moment the code is very simple, you hold down UP and force is applied in the direction you're pointing which makes it feel like the ship in asteroids.
It seems to me the next thing I need to do is compare the direction the car is pointing with the direction it's actually travelling and apply some sideways force to make it slow down in the sideways direction but also transfer some of that force to the forward direction so it keeps going in the direction it's now pointing.
I'm a bit confused as to how I go about doing this so any advice would be most welcome.