如何检测多边形上的碰撞

时间:2015-08-12 18:33:07

标签: javascript craftyjs

我试图检测我的播放器(只是一个正方形)和一个带CraftyJS的多边形之间的碰撞:

// Init Crafty:
Crafty.init();
Crafty.canvas.init();

var AttackPoly = new Crafty.polygon([
    [-8, 6],
    [0, -8],
    [8, -14],
    [16, -8],
    [24, 6]
]);

attackEnt = Crafty.e("AttackRange, 2D, Canvas, Collision, SolidHitBox, Color").attr({x:50, y:50}).collision(AttackPoly);

Crafty.e("2D, Canvas, Color, Fourway, Collision, Tester").attr({
    x: 100,
    y: 60,
    w: 4,
    h: 4
}).color("orange");

Crafty.e("2D, Canvas, Color, Fourway, Collision, Tester").attr({
    x: 100,
    y: 50,
    w: 4,
    h: 4
}).color("orange");

Crafty.e("2D, Canvas, Color, Fourway, Collision, Tester").attr({
    x: 100,
    y: 40,
    w: 4,
    h: 4
}).color("orange");

Crafty("Tester").bind("EnterFrame", function () {
    this.x -= .2
    if (this.hit("AttackRange")) this.color("aqua")

});

击中多边形的方块不会改变它们的颜色。我错过了什么?

小提琴:http://jsfiddle.net/c3597/32/

1 个答案:

答案 0 :(得分:1)

我明白了:Polygon必须在一个边界矩形内:

Crafty
  .e('AttackRange, 2D, Canvas, Collision, SolidHitBox, Color')
  .attr({x:50, y:50, w: 100, h: 100})
  .collision(new Crafty.polygon([
    [0, 0],
    [100, 50],
    [0, 100]
  ]))
  .color('blue'); 

小提琴:http://jsfiddle.net/c3597/33/