Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bouncing ball
var gameScreen = document.getElementById("gameScreen");
var context = gameScreen.getContext("2d");
context.fillStyle = "#FFFFFF";
context.font = "8px Sans-Serif";
context.fillText("Pong!", 10, 10);
var ball = {
x : 50,
y : 50,
width : 5,
height : 5,
x_direction : 1,
y_direction : 1
};
var previousBall = ball;
var boundary = {
x1: 20,
x2: 200,
y1: 20,
y2: 120
};
context.fillStyle = "#FF00FF";
context.strokeStyle = "#FF00FF";
context.strokeRect(boundary.x1, boundary.y1, boundary.x2 - boundary.x1, boundary.y2 - boundary.y1);
var timer = setInterval(updateGameScreen, 10);
function updateGameScreen() {
context.clearRect(previousBall.x, previousBall.y, previousBall.width, previousBall.height);
previousBall = ball;
if (ball.x_direction === 1) {
ball.x += 2;
if (ball.x_direction === 1 && ball.x > boundary.x2 - 10) {
ball.x_direction = -1;
}
}
if (ball.x_direction === -1){
ball.x -= 2;
if (ball.x_direction === -1 && ball.x < boundary.x1 + 10) {
ball.x_direction = 1;
}
}
if (ball.y_direction === 1) {
ball.y++;
if (ball.y_direction === 1 && ball.y > boundary.y2 - 7) {
ball.y_direction = -1;
}
}
if (ball.y_direction === -1){
ball.y--;
if (ball.y_direction === -1 && ball.y < boundary.y1 + 7) {
ball.y_direction = 1;
}
}
context.fillRect(ball.x, ball.y, ball.width, ball.height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment