Hi, I’m kinda new here and need a little help!
I made a line that moves along the arrrow keys and speeds up when the space bar is pressed. In my code when the line changes its direction it makes a corner (see left), but I want to make the line turn gradually in an angle (like a vehicle would turn in reality), as right.
For example: as long as the left arrow is pressed, it keeps turning to the left.
I’m not an expert in p5.js, but I think it can be fixed with sin() and/ or cos(), I just couldn’t find a solution. Is there somebody who can help me with this?
class Branch {
constructor(tempX, tempY) {
this.x = tempX;
this.y = tempY;
this.prevx = tempX;
this.prevy = tempY;
this.speed = 1;
this.dirX = 0;
this.dirY = 0;
}
update() {
this.move();
this.show();
this.walls();
}
move() {
this.prevx = this.x;
this.prevy = this.y;
this.x += this.dirX * this.speed;
this.y += this.dirY * this.speed;
}
setDirection(x, y) {
this.dirX = x;
this.dirY = y;
}
addSpeed() {
this.speed++;
}
show() {
stroke(0);
strokeWeight(1);
line(this.prevx, this.prevy, this.x, this.y);
}
walls() {
if (this.x > windowWidth) {
this.x = 0;
} else if (this.x < 0) {
this.x = windowWidth;
} else if (this.y > windowHeight) {
this.y = 0;
} else if (this.y < 0) {
this.y = windowHeight;
}
}
}
let branch = [];
function setup() {
background(255);
createCanvas(windowWidth, windowHeight);
branch = new Branch(width / 2, height / 2);
}
function draw() {
branch.update();
}
function keyPressed() {
if (keyCode === UP_ARROW) {
branch.setDirection(0, -1);
} else if (keyCode === DOWN_ARROW) {
branch.setDirection(0, 1);
} else if (keyCode === LEFT_ARROW) {
branch.setDirection(-1, 0);
} else if (keyCode === RIGHT_ARROW) {
branch.setDirection(1, 0);
}
else if (keyCode === 32) { // SPACE_BAR
branch.addSpeed();
}
}