Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
p5.js: Why is my image duplicating every time I use the keyPressed() function?

I am trying to navigate the legoman image across the canvas using the arrow keys. However, the image seems to duplicate instead (see image).

legoman p5.js

How do I get the image to move without leaving a trail of images behind?

See code:

function keyPressed() {
  if (keyCode === UP_ARROW) {
    y = y - 10;
  } else if (keyCode === DOWN_ARROW) {
    y = y + 10;
  }
  if (keyCode === LEFT_ARROW) {
    x = x - 10;
  } else if (keyCode === RIGHT_ARROW) {
    x = x + 10;
  }

  if (keyCode === RETURN) {
    background(255);
  }
}

Also here is the link to my file if that helps: https://editor.p5js.org/emmajaneculhane/sketches/NDWUd0-Vj

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The issue is no longer present in the p5 editor sketch you've shared.

That is because you're calling

background(currentBackground);

in keyPressed() in that version.

Indeed, background() clears the previously rendered image with a flat colour which is the behaviour you want to avoid trails.

You would need to set currentBackground to a different value once you click one of the 8 colour circles.

For example:

if (dRed < 30 / 2 && mouseIsPressed) {
    currentBackground = redB;
  }

instead of:

if (dRed < 30 / 2 && mouseIsPressed) {
    background(redB);
  }

The same logic would apply to the rest of the colour circles.

Additionally if you want to make the keys a bit more responsive you can check if a key is pressed in draw():

function draw() {
  
  if(keyIsPressed){
    if (keyCode === UP_ARROW) {
      y = y - 10;
    } else if (keyCode === DOWN_ARROW) {
      y = y + 10;
    }
    if (keyCode === LEFT_ARROW) {
      x = x - 10;
    } else if (keyCode === RIGHT_ARROW) {
      x = x + 10;
    }
  }
  
  background(currentBackground);
  //...the rest of your draw code goes here

}

It might also help to have some boundary conditions so the LEGO figure doesn't go outside of bounds (e.g. only increment x if it's greater than 0 and smaller than the width of the sketch, same applies for y)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!