Posted by:
Ryan
I was trying to figure out how to get basic
collision detection working from scratch, which is essentially getting boxes to know that they've intersected each other and to react appropriately. And while I was prototyping it out in Javascript, I was able to get some rectangular boxes to collide, and the whole thing looked a bit like Pong.
So I made a simple Pong copycat with just Javascript code and by repositioning <div> tags, and you can play with it
here.
Player 1: Move with 'W' and 'S'
Player 2: Move with 'UP' arrow and 'DOWN' arrow
Reset game: Press 'Enter'
Because of the way browser inputs are handled, rapidly tapping the keys works much better than holding them down. Also, the game is only 500 pixels wide because I originally planned to embed it into a post with an iframe.
P.S. If you're interested, my collision detection function is essentially this:
var a = object1.x,
b = object1.x + object1.width,
c = object2.x,
d = object2.x + object2.width,
e = object1.y,
f = object1.y + object1.height,
g = object2.y,
h = object2.y + object2.height;
if (a > d || c > b || e > h || g > f) {
// rectangular objects are not colliding
} else {
// rectangular objects are colliding
}
Note that this code depends on the objects intersecting for at least one frame, so it won't work for really fast objects (or really thin objects).
Awesome! If you end up making anything, I'd love to see it!
But to let you know, Javascript is kind of a horrible environment for game coding. I just happened to use JS because it was sort of a quick, easy thing I could write. For a real game, I would maybe recommend ActionScript 3 (Flash) or something. But if you decide to actually go the JS route anyway, the <canvas> tag is a much better alternative to moving absolutely positioned <div>s around a screen like I did.