Game Design with Crafty.js – Part 2

Our game continues where we left off with a player Entity and a coin entity. Use this Pen to get started.

We have our player Entity.

Crafty.e('2D, DOM, Color, Fourway')
.attr({x: 0, y: 0, w: 20, h: 30})
.fourway(3)
.color("#0f0")

We have our coin Entity.

Crafty.e('2D, DOM, Color, coin')
.attr({x:200, y:250, w:10, h: 10})
.color('#999');

Collisions

Let’s add a collision so that when the player collides with the coin he wins.

To win: Collide with a Coin

Crafty.e('2D, DOM, Color, Fourway, Collision')
.attr({x: 0, y: 0, w: 20, h: 30})
.fourway(3)
.collision()
.color("#0f0")
  .onHit("coin", function(e) {
       alert("You Win!");
  });

Now, Let’s add another collision so that when collides with a bad coin he loses.

To lose: Collide with a ‘Bad Coin’

First Let’s add the bad coin.

Crafty.e('2D, DOM, Color, badcoin')
.attr({x:200, y:250, w:10, h: 10})
.color('#f00');

Now, Let’s add the collision with the bad coin to the player

Crafty.e('2D, DOM, Color, Fourway, Collision')
.attr({x: 0, y: 0, w: 20, h: 30})
.fourway(3)
.collision()
.color("#0f0")
.onHit("coin", function(e) {
alert("You Win!");
})
.onHit("badcoin", function(e) {
this.destroy();
alert('You lose');

});

Question: What is this in the function above? What is destroyed when you collide with the bad coin?

Just for Fun: Change this.destroy() to this.h = this.h / 2; What happened?

Moving Characters

Let’s make the coins move on their own!

Add this to the coin.

Crafty.e('2D, DOM, Color, coin')
.attr({x:200, y:250, w:10, h: 10})
.bind('EnterFrame', function() {
this.x = this.x + 1;
})
.color('#999');

Question: What can you do to keep your coin on the screen? (Hint: The game screen is 500 pixels.)

Let’s add an if statement to our coin:

Crafty.e('2D, DOM, Color, coin')
.attr({x:200, y:250, w:10, h: 10})
.bind('EnterFrame', function() {
this.x = this.x + 1;
if (this.x > 500) {
this.x = 0;
}
})
.color('#999');

Questions

  • What is a Collision?
  • When the player collides with a coin, is the collision code added to the player of the coin?
  • What did we have to add to our moving character to keep him from running off the screen?