Now that we’ve done the obligatory Hello World let’s make something more interesting.
As before, you need to initialize your game engine. Paste the following into main.coffee
window.engine = Engine backgroundColor: Color('sky blue') canvas: $('canvas').powerCanvas() includedModules: ['Box2D'] PHYSICS_DEBUG_DRAW: false
The line to pay attention to is
includedModules: ['Box2D']. This tells the engine that you want to enable Box2D physics. We make our game libraries as modular as possible so you aren’t constrained when you want to build that Frankensteinian aberration of a game.
Next, add the following
obj = engine.add color: Color('pink') dynamic: true includedModules: ['Physical'] friction: 0.1 width: 50 height: 50 x: 50 y: 50
As with the engine initialization, you need
includedModules: ['Physical'] so this object behaves according to the laws of Box2D physics. There are a few more important properties here.
dynamic: true tells Box2D that the object is a dynamic body (one that moves), rather than static body. Lastly,
friction: 0.1 assigns the object a coefficient of friction.
Next we want to make walls that our pink box can run into.
2.times (n) -> engine.add color: Color('beige') includedModules: ['Physical'] width: 640 height: 10 friction: 0.5 restitution: 0 x: n y: n * 470 2.times (n) -> engine.add color: Color('beige') includedModules: ['Physical'] width: 10 height: 480 x: n * 630 y: n
There isn’t much new here, except for our extension method
Number#times. It works just like the Ruby counterpart. Check out the documentation link in your file tree if you want to learn more about it. One last thing to mention is that we are setting the floor’s friction and a new physics property,
restitution: 0, which amounts to bounciness.
The last thing we need to do is enable some player input.
engine.bind 'update', -> if keydown.left obj.applyImpulse Point(-50, 0) if keydown.right obj.applyImpulse Point(50, 0) if keydown.space engine.add color: Color('navy blue') duration: 75 dynamic: true friction: 1 includedModules: ['Physical'] restitution: 0 rotatable: true width: 10 height: 10 y: 20 x: rand(600) + 20 engine.start()
We start off with
engine.bind 'update', ->. This will execute the function we provide each time the engine updates.
keydown.left checks to see if the player is pressing left on their keyboard and if so, applies an impulse to the pink box we made earlier. If
keydown.space is true we add ‘rain’ objects to the system.
There are two new properties on these rain guys. First
duration: 75 destroys the rain object, and the corresponding object in the Box2D simulation, after 75 engine updates.
rotatable: true enables the rain objects to rotate based on the objects the collide with.
engine.start() starts the game.