<h2>Collisions in Crafty</h2>
<div id="crafty-game"></div>
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Lato';
  margin: 20px auto;
  width: 600px;
  text-align: center;
}

h2 {
  margin: 20px 0;
}

#crafty-game {
  border: 1px solid black;
}
var stageWidth = 600;
var stageHeight = 400;
var gameScore = 0;

Crafty.init(600, 400, document.getElementById('crafty-game'));

Crafty.e("2D, Canvas, Color, Obstacle")
  .attr({
    x: 250,
    y: 100,
    w: 100,
    h: 200
  })
  .color('black');

Crafty.e("2D, Canvas, Color, Collision")
  .attr({
    x: 180,
    y: 60,
    w: 40,
    h: 40,
    hSpeed: 2,
    rotation: 45
  })
  .color('orange')
  .checkHits('Obstacle')
  .bind('EnterFrame', function() {
    this.x += this.hSpeed;

    if (this.x < 150) this.hSpeed *= -1;
    if (this.x > 460) this.hSpeed *= -1;
  })
  .bind("HitOn", function(hitData) {
    Crafty("Obstacle").color('red');
    console.log(hitData);
  })
  .bind("HitOff", function(comp) {
    Crafty("Obstacle").color('black');
  });

External CSS

  1. https://fonts.googleapis.com/css?family=Lato:

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/crafty/0.7.1/crafty-min.js