Using constrain() p5 js

Viewed 40

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;
    }
  }
}

1 Answers

You need to assign x to another variable each time you do a constrain

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;

let img; // Declare variable 'img'.
let speed = 10;

function setup() {
  createCanvas(2000, 720);
  img = loadImage('s.jpg'); // Load the image
}

function draw() {
  background(220);
  
  let xc = constrain(x, leftWall, rightWall);
  
  image(img, xc, y);
  
  // Draw the walls.
  stroke(150);
  line(leftWall, 0, leftWall,height);
  line(rightWall, 0, rightWall,height);

  
   if (keyIsDown(A_Key)) {
    x -= speed;
  }
  if (keyIsDown(D_Key)) {
    x += speed;
  }
}

This is for reference:

https://p5js.org/reference/#/p5/constrain

Related