Created
September 12, 2022 17:01
-
-
Save AdhirRamjiawan/10091a0c83d872fb38f092cfcb106790 to your computer and use it in GitHub Desktop.
Bouncing ball
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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