Question

My concept is rather simple. Animate an image one way, then make it come back.

var xPos = 10;

function main(){
    window.requestAnimationFrame(main);
    var canvas = document.getElementById("myCanvas");
    var c = canvas.getContext("2d");

    //Initialize images
    var img = new Image();
    img.src = "goomba.png";

    c.clearRect(0,0,500,500);
    c.drawImage(img,xPos,10);


    //increment coordinates
    if(xPos <= 250){
        xPos+=2;
    }
    else if(xPos >= 250){
        xPos-=2;
    }
}
window.requestAnimationFrame(main);

I already know what the problem is with my code. When the xPos goes over 250, then the second if statement becomes true. However, once it goes below 250, the first if becomes true again. So I know what the problem is, I just dont know how to fix it. Any help is appreciated!

Was it helpful?

Solution

Have a velocity variable (positive is right, negative is left, amplitude is number of pixels to change each loop):

var xVelocity = 2;

And use it to determine what to add to the xPos each loop:

xPos += xVelocity;

Then set it based on xVelocity and xPos so that the image will "bounce":

if(xVelocity > 0){
    if(xPos > 250){
        xVelocity = -2;
    }
} else {
    if(xPos < 10){
        xVelocity = 2;
    }    
}

OTHER TIPS

http://jsbin.com/uweyam/1/edit

is this what you want? Or do you want to stop it at the left edge?

UPD.: You can also make it bounce like this - http://jsbin.com/uweyam/4/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top