Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Created December 17, 2014 23:35
Show Gist options
  • Save Aleksey-Danchin/3ceacb607baaf55adb49 to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/3ceacb607baaf55adb49 to your computer and use it in GitHub Desktop.
Balls with phisics.
<canvas id="canvasElement" style="border: 1px solid black;"></canvas>
<script>
setup(); loop();
setInterval(loop, 0);
/////////////////////////////////////////////////
var canvas, context, balls, PI2;
/////////////////////////////////////////////////
function setup () {
canvas = document.getElementById('canvasElement');
context = canvas.getContext('2d');
canvas.width = canvas.height = 500;
PI2 = 2 * Math.PI;
balls = [];
balls.push(new Ball({x: 100, y: 100, sx: 0.05, sy: 0}));
balls.push(new Ball({x: 100, y: 125, sx: 0.07, sy: 0.01}));
balls.push(new Ball({x: 100, y: 150, sx: 0.09, sy: 0.04}));
}
/////////////////////////////////////////////////
function loop () {
clearCanvas();
ballsPhysics();
drawEarth();
drawBalls();
}
/////////////////////////////////////////////////
function ballsPhysics () {
balls.forEach(function (ball) { ball.physics(); });
}
function drawBalls () {
balls.forEach(function (ball) { ball.draw(); });
}
function drawEarth () {
context.beginPath();
context.lineWidth = 5;
context.strokeStyle = 'black';
context.moveTo(0, 450);
context.lineTo(500, 450);
context.stroke();
}
function clearCanvas () {
canvas.width = canvas.width;
}
/////////////////////////////////////////////////
function Ball (_param_) {
var __ball = {};
////////////////////
__ball.x = _param_.x ? _param_.x : 0;
__ball.y = _param_.y ? _param_.y : 0;
__ball.r = _param_.r ? _param_.r : 5;
__ball.speed = {x: _param_.sx ? _param_.sx : 0.5, y: _param_.sy ? _param_.sy : 0};
////////////////////
__ball.draw = draw;
__ball.physics = physics;
////////////////////
return __ball;
////////////////////
function draw () {
context.beginPath();
context.arc(__ball.x, __ball.y, __ball.r, 0, PI2);
context.stroke();
context.fill();
}
function physics () {
if (__ball.y >= 450 - __ball.r)
__ball.speed.y = -__ball.speed.y;
if (__ball.x <= __ball.r || __ball.x >= 500 - __ball.r)
__ball.speed.x = -__ball.speed.x;
__ball.speed.y += 0.07;
__ball.x += __ball.speed.x;
__ball.y += __ball.speed.y;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment