Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda