Bounce an Image
We will now bounce our image around the screen. Follow the steps below
- Instead of updating the x/y by 1 each time we will update the x/y by our X velocity(direction) and our Y velocity(direction). These are saved in the xVol and yVol varialbes.
//todo: update position
x= x + xVol;
y= y + yVol;
- when we hit a wall we need to change our velocity to go the other way. When we hit the far wall we will go backwards by changing the velocity to a negivty number, -1.
//todo: bounce off wall
if(x > 350) xVol = -3;
if(x < 0) xVol = 3;
if(y > 550) yVol = -1;
if(y < 0) yVol = 1;
- Lets try something, comment out the ctx.clearRect function by placing two slashes in front of it.
// ctx.clearRect(0, 0, canvas.width, canvas.height);
x=
y=