Detekcija sudara kutijom
by Daman Daman
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script>
<div id="cr-stage"></div>
<p>Move the rectangle with arrow keys. Green means collision, blue means no collision.</p>
JavaScript
Crafty.init(200, 200);
var dim1 = {x: 5, y: 5, w: 50, h: 50}
var dim2 = {x: 20, y: 10, w: 60, h: 40}
var rect1 = Crafty.e("2D, Canvas, Color").attr(dim1).color("red");
var rect2 = Crafty.e("2D, Canvas, Color, Keyboard, Fourway").fourway(2).attr(dim2).color("blue");
rect2.bind("EnterFrame", function () {
if (rect1.x < rect2.x + rect2.w &&
rect1.x + rect1.w > rect2.x &&
rect1.y < rect2.y + rect2.h &&
rect1.h + rect1.y > rect2.y) {
// collision detected!
this.color("green");
} else {
// no collision
this.color("blue");
}
});