seanstacks
seanstacks

Reputation: 11

Create an application with one DOM element that is always moving right, at a speed of 2 pixels per update

Create an application with one DOM element that is always moving right, at a speed of 2 pixels per update. When it it reaches 800 pixels to the right (a 'left' property of '800px'), return it to the far left of the screen (a 'left' property of '0px').

This is what I have so far but I can't get the ball to bounce to the left.

var ball = document.querySelector(".ball");
var animationArea = document.querySelector("#animationArea");

setInterval(update, 30); //this will call the tick function every 1000 miliseconds
var x = 0;
var y = 0;
var velocityX=2;
var velocityY=2;

function update() {
    //run your update code
    x = x + velocityX;
    y = y + velocityY;
    ball.style.right = x + "px";
    ball.style.left = y + "px";

    if (x>=800) {
        //bounce the ball
        velocityX = 2; 
        y = 300;
    }
    requestAnimationFrame(update);
}

Upvotes: 0

Views: 31

Answers (1)

Punit
Punit

Reputation: 1976

The solution is in the question itself:

When it it reaches 800 pixels to the right (a 'left' property of '800px'), return it to the far left of the screen (a 'left' property of '0px').

if (x >= 800) { // When it it reaches 800 pixels to the right (a 'left' property of '800px')
  x = 0; // return it to the far left of the screen (a 'left' property of '0px')
}

Upvotes: 1

Related Questions