It's a question about how to use the code of ''Clear''

I have some problems when I write code. I try to design a game like a gold miner, and I want to use the left and right keys to move my hook. But when I write codes like this:

function setup() {
createCanvas(windowWidth, windowHeight);
background(220);
imageMode(0,0);
image(img11,x,175, 90, 75);
}

function draw() {
image(img11,x,175, 90, 75);
if(keyIsPressed){
if(keyCode == 37){
x-=speed;
}
if(keyCode == 39){
x +=speed;
}
}
clear();
image(img11,x,175, 90, 75);

My pre-designed background will disappear. But if without

clear();
image(img11,x,175, 90, 75);

these two lines of codes, my hook will have afterimages. It can’t move smoothly. I want to keep my background and make hook moves correctly.
How do I solve this problem? Help!!


function draw() {
clear();
image(img11,x,175, 90, 75);

if(keyIsPressed){
if(keyCode == 37){
x-=speed;
}
if(keyCode == 39){
x +=speed;
}
}

Thank you for your reply.
But my background still disappeared and I don’t know why.
Is there any solution that can fix this problem?

Did you try

image(img11,x,175);

Do you realize, your x can be < 0 ? Therefore your image must be very wide.

maybe your speed is too high?

Please post your entire code

Warm regards,

Chrisir

var imgstart;
var imgplay;
var imgbutton;
var imgscene;
var gameScreen=0;
var x=200;
var speed=2;
function setup() {
createCanvas(windowWidth, windowHeight);
background(220);
imageMode(0,0);
}
function preload() {
img11 = loadImage(‘hook.png’);
}
function initScreen() {
gameScreen=0;
image(imgstart,-300,-440);
}

function gameplay() {
gameScreen=1;
image(imgplay,-300,-440);
image(imgbutton, 600, 400);
}

function gamestart() {
gameScreen=2;
image(imgscene,-300,-440);
}

function keyPressed(){
if(keyCode == 32){
gameScreen=1;
}
}

function mouseClicked() {
if (gameScreen == 1) {
gamestart(gameScreen = 2);
}
}
function draw() {
clear();
image(img11,x,175,90, 75);
if(keyIsPressed){
if(keyCode == 37){
x-=speed;
}
if(keyCode == 39){
x +=speed;
}
}

By the way, I tried image(img11,x,175); , and my image is very wide. Is that what makes the background disappear?
Thanks again for your reply!

Do you mean this image???

Then you need to display it at start of draw()

Yes,
I tried this and it works !

function draw() {
image(imgscene,-300,-440);
image(img11,x,175, 90, 75);
if(keyIsPressed){
if(keyCode == 37){
x-=speed;
}
if(keyCode == 39){
x +=speed;
}
}

Thank you!

1 Like