I am trying to navigate the legoman image across the canvas using the arrow keys. However, the image seems to duplicate instead (see image).
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
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)