Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda