Created
December 14, 2016 20:35
-
-
Save bzdgn/b7db3c9e5ebb63e253ecad7cd3e96eec to your computer and use it in GitHub Desktop.
2D Single Bouncing Ball Demo
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>2D Single Bouncing Ball Demo</title> | |
</head> | |
<body> | |
<canvas width="800" height="600" id="mainCanvas" > | |
</canvas> | |
<p><input type="Button" VALUE=" start " onClick="doTimer()"></p> | |
<p><input type="Button" VALUE=" stop " onclick="stopTimer()"></p> | |
<script> | |
<!-- Written by Levent Divilioglu --> | |
<!-- 14.12.2016 --> | |
(function () { | |
canvas = document.getElementById('mainCanvas'); | |
ctx = canvas.getContext("2d"); | |
WIDTH = canvas.width; | |
HEIGHT = canvas.height; | |
ctx.fillStyle="black"; | |
ctx.fillRect( 0, 0, WIDTH, HEIGHT); | |
MAX_VELOCITY = 10; | |
centerX = WIDTH / 2; | |
centerY = HEIGHT / 2; | |
RADIUS = 20; | |
var initials = initGame(); | |
BALL = initials.ball; | |
})(); | |
function initGame() { | |
return { "ball": generateBall(RADIUS) }; | |
} | |
function animateGame() { | |
clearScreen(); | |
gameHandler(); | |
} | |
function gameHandler() { | |
BALL.x += BALL.v_x | |
if( (BALL.v_x < 0) && (BALL.x - BALL.r < 0) || (BALL.v_x > 0) && (BALL.x + BALL.r > WIDTH) ) { | |
BALL.v_x = -BALL.v_x; | |
} | |
BALL.y += BALL.v_y | |
if( (BALL.v_y < 0) && (BALL.y - BALL.r < 0) || (BALL.v_y > 0) && (BALL.y + BALL.r > HEIGHT) ) { | |
BALL.v_y = -BALL.v_y; | |
} | |
drawBall(); | |
} | |
function drawBall() { | |
ctx.beginPath(); | |
ctx.arc(BALL.x, BALL.y, BALL.r, 0, 2 * Math.PI, false); | |
ctx.fillStyle = 'white'; | |
ctx.fill(); | |
} | |
function clearScreen() { | |
ctx.clearRect( 0, 0, WIDTH, HEIGHT ); | |
ctx.fillStyle="black"; | |
ctx.fillRect( 0, 0, WIDTH, HEIGHT ); | |
} | |
function doTimer() { | |
timerID = setInterval( "animateGame()", 20 ); | |
} | |
function stopTimer() { | |
clearInterval( timerID ); | |
} | |
function generateBall(radius) { | |
var x = getPositiveRandom(WIDTH - radius); | |
var y = getPositiveRandom(HEIGHT - radius); | |
var v_x = getPositiveRandom(MAX_VELOCITY); | |
var v_y = getPositiveRandom(MAX_VELOCITY); | |
var ball = { "r": radius, "x": x, "y": y, "v_x": v_x, "v_y": v_y }; | |
return ball; | |
} | |
function getRandom(limit) { | |
var sign = Math.ceil( Math.random() * 100 ); | |
if(sign < 50) | |
sign = -1; | |
else | |
sign = 1; | |
var num = sign * Math.ceil( (Math.random() * limit-1) + 1); | |
return num; | |
} | |
function getPositiveRandom(limit) { | |
var num = Math.ceil( (Math.random() * limit-1) + 1); | |
return num; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output;