I'm trying to create a little car simulator in p5.js that has a bird's eye view of a track. So far I've been able to create the car and get it to move (up, down, left, right), but that's not how you drive in real life. I need to only be able to go forwards, backward, and rotate the car while going in those 2 directions to steer.
What I've done so far:
sketch.js
// Declares global variables
const h = window.innerHeight;
const w = window.innerWidth;
var car;
var borders = [];
var pos = {
x: 200,
y: 200,
angle: 0
}
function setup () {
// Creates the canvas
background ( '#000000' );
createCanvas ( 400, 400 );
angleMode ( DEGREES );
rectMode ( CENTER );
stroke ( 255 );
// Creates the car
car = new Car();
}
function draw () {
// Clears the canvas
background ( '#000000' );
// Moves the car
if ( keyIsDown ( UP_ARROW ) ) {
pos.y -= 2;
}
if ( keyIsDown ( RIGHT_ARROW ) ) {
pos.angle += 2;
}
if ( keyIsDown ( DOWN_ARROW ) ) {
pos.y += 2;
}
if ( keyIsDown ( LEFT_ARROW ) ) {
pos.angle -= 2;
}
// Displays the car on the canvas
translate(pos.x, pos.y);
rotate(pos.angle);
car.show();
}
and the car class
class Car {
// Defines the class
constructor ( ) {
this.pos = createVector ( 0, 0 );
this.width = 10;
this.length = 20;
}
// Displays the car on the canvas
show () {
rect ( this.pos.x, this.pos.y, this.width, this.length );
}
}
When I run this code, I can go forwards and backward, but when I try to steer and go forwards, I just go up, not in the direction the car is facing.
I know why this is happening (the Y-axis isn't relative to the rotation of the car), but I don't know how to do it any other way.