I'm trying to stop image(player, x, y) from going off the road and stop at leftWall and rightWall for a small p5 js project. No matter how I've tried implementing constrain(n, low, high) it will not work. So I've settled on using this instead:
if (x < leftWall) { x = leftWall;}
Can someone tell me how to correctly use constrain in this code?
const A_Key = 65;
const D_Key = 68;
const initialX = 350;
const initialY = 550;
let x = initialX;
let y = initialY;
let leftWall = 54;
let rightWall = 516;
function draw() {
background(bg);
image(player, x, y);
if (keyIsDown(A_Key)) {
x -= speed;
if (x < leftWall) {
x = leftWall;
}
}
if (keyIsDown(D_Key)) {
x += speed;
if (x > rightWall) {
x = rightWall;
}
}
}