Intro to Crafty - Collision
Fifth code demo slide from a crafty js presentation: https://github.com/ajacksified/Craftyjs-Presentation
by barbados22
HTML
<script src="https://rawgithub.com/craftyjs/Crafty/release/dist/crafty-min.js"></script>
<h1>Demo 5: Collision</h1>
<button id="addBox">Add Box</button>
<button id="addMovableBox">Add Movable Box</button>
<p>Points: <span id="points">0</span></p>
<div id="cr-stage"></div>
JavaScript
var width = 400,
height = 300,
points = 0;
Crafty.init(width, height);
Crafty.c("Box", {
init: function() {
this.addComponent("2D, Canvas, Color");
},
makeBox: function(color){
var x = Math.random() * 100 >> 0;
var y = Math.random() * 100 >> 0;
this.attr({x: x, y: y, w: 20, h: 20}).color(color);
return this;
}
});
Crafty.c("MovableBox", {
init: function(){
this.addComponent("Box, Fourway, Collision");
this.fourway(2);
this.collision();
this.onHit("Box", function(target) {
points++;
$("#points").text(points);
target[0].obj.destroy();
});
}
});
$("#addBox").bind("click", function(){
var box = Crafty.e("Box").makeBox("#FF0000");
});
$("#addMovableBox").bind("click", function(){
var box = Crafty.e("MovableBox").makeBox("#00FF00");
});