<h2>Collisions in Crafty - Custom Hitbox</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'));

var game_assets = {
  "sprites": {
    "http://opengameart.org/sites/default/files/player64-draft-sinc.png": {
      tile: 64,
      tileh: 48,
      map: {
        space_ship: [0, 0]
      }
    }
  }
};

Crafty.load(game_assets);

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

var spaceShip = Crafty.e("2D, Canvas, space_ship, Collision, WiredHitBox")
  .attr({
    x: 380,
    y: 260,
    hSpeed: 1,
    hitShape: 0
  })
  .debugStroke('green')
  .checkHits('Obstacle')
  .bind('EnterFrame', function() {
    this.x += this.hSpeed;
    if (this.x > 400) {
      this.x = 80;
      this.hitShape++;
      if(this.hitShape%2!==0) {
      this.collision(8, 0, 0, 48, 70, 48);
      } else {
       this.collision(0, 0, 64, 0, 64, 48, 0, 48); 
      }
    }
  })
  .bind("HitOn", function(hitData) {
    Crafty("Obstacle").color('blue');
    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