Skip to content

Instantly share code, notes, and snippets.

@zgchurch
Created March 17, 2011 16:29
Show Gist options
  • Save zgchurch/874626 to your computer and use it in GitHub Desktop.
Save zgchurch/874626 to your computer and use it in GitHub Desktop.
pong with HTML5 Canvas: left player uses keyboard, right player uses mouse
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var canvas = $('canvas#pong');
var context = canvas[0].getContext('2d');
var players = [{position: {x: 10, y: 30}}, {position: {x: 900, y: 00}}];
var config = {player: {width: 30, height: 150}};
var ball = {position: {x: 100, y: 100}, velocity: {x: 3, y: 0}, width: 15, height: 15};
var angle_coefficient = -1/50;
ball.check = function(players) {
var x = this.position.x;
var y = this.position.y;
for (var i in players) {
var player = players[i];
if (x + this.width >= player.position.x &&
x < player.position.x + config.player.width &&
y > player.position.y && y < player.position.y + config.player.height) {
// reverse x velocity
ball.velocity.x *= -1;
// set y velocity
var player_middle = player.position.y + (config.player.height / 2);
var ball_middle = ball.position.y + (ball.height / 2);
ball.velocity.y = (player_middle - ball_middle) * angle_coefficient;
}
}
if (ball.position.y <= 0) {ball.velocity.y *= -1};
if (ball.position.y >= canvas.height() + ball.height) ball.velocity.y *= -1;
};
function draw() {
context.clearRect(0, 0, canvas.width(), canvas.height());
for (var i in players) {
context.fillRect(players[i].position.x, players[i].position.y, config.player.width, config.player.height);
}
context.fillRect(ball.position.x, ball.position.y, ball.width, ball.height);
}
$(document).keydown(function(key) {
var delta = 8;
if (key.keyCode == 40) { if (players[0].position.y <= canvas.height() - delta - 150) players[0].position.y+=delta };
if (key.keyCode == 38) { if (players[0].position.y > 0) players[0].position.y-=delta };
draw();
});
var mouse_position = players[1].position.y;
$(document).mousemove(function(event) {
mouse_position = event.clientY;
});
setInterval(function() {
mouse_velocity = (mouse_position - players[1].position.y - config.player.height/2 ) / 30;
}, 10);
setInterval(function() {
ball.position.x += ball.velocity.x;
ball.position.y += ball.velocity.y;
players[1].position.y += mouse_velocity;
ball.check(players);
draw();
}, 15);
draw();
});
</script>
<canvas width="1270" height="750" id='pong'></canvas>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment