Game Design in JavaScript with Crafty.js

Go to the Pen on codepen.io

Add our first game Entity:

Crafty.e('2D, DOM, Color').attr({x: 0, y: 0, w: 100, h:100}).color('#300');

Lets make our Entity move:

Crafty.e('2D, DOM, Color, Fourway').attr({x: 0, y: 0, w: 100, h:100}).color('#300').fourway(3);

You should now be able to move the Entity with the arrow keys! Cool!

Let’s add our second game Entity.

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

Let’s Create a Collision between our two Entities. On our first entity add:

Crafty.e('2D, DOM, Color, Fourway, Collision').attr({x: 0, y: 0, w: 100, h: 100}).color('#300').fourway(3).collision().onHit("coin", function(e) {
e[0].obj.destroy();
});

Now, when the two entities collide the coin should be destroyed.

Try it: What happens when you comment out the line with .destroy()?

Let’s create a ‘score’ variable. Add the following to your code:

var score = 0;
Crafty.e('2D, DOM, Color, Fourway, Collision').attr({x: 0, y: 0, w: 100, h: 100}).color('#300').fourway(3).collision().onHit("coin", function(e) {
e[0].obj.destroy();

});

Now, When our player collides with the coin we’ll get a point.

Crafty.e('2D, DOM, Color, Fourway, Collision').attr({x: 0, y: 0, w: 100, h: 100}).color('#300').fourway(3).collision().onHit("coin", function(e) {
e[0].obj.destroy();
   score = score + 1;
});

We should be scoring a point each time the player collides with the coin.

Let’s Win the game when we score 10 or more points, when score is greater than or equal to 10.

Crafty.e('2D, DOM, Color, Fourway, Collision').attr({x: 0, y: 0, w: 100, h: 100}).color('#300').fourway(3).collision().onHit("coin", function(e) {
e[0].obj.destroy();
score = score + 1;
   if (score >= 10) {
alert('You Win.');
}

});

Questions:

  • We added something to the Entity to make it move. (‘fourway’) Why is it called that?
  • When two Entities bump into each other it is called a ________ ?