1

在 CraftyJS 中,我如何阻止我的播放器实体剪辑到其他实体中?

这是我的对象:

        Crafty.c("Mushroom", {
        init: function() {
            this.addComponent("collision");
            this.collision(new Crafty.polygon([[8,8],[24,8],[24,24],[8,24]]));
        }
    });

    var mushroom = Crafty.e("2D, canvas, mushroomRed, Mushroom")
    .attr({x: 200, y: 150, z:1, w: 32, h: 32});

这是我的播放器 onHit:

.onhit("mushroomRed", function() {
            this.x += this._speed;
            this.stop();
        }

只有当我从某个角度接近它时它才会起作用,否则它会变得混乱。

建议?

4

1 回答 1

3

看起来你正在使用

this.x += this._speed;

让玩家在碰撞后远离蘑菇。但是因为你只是在 x 方向上移动它,所以如果你从顶部或底部碰撞它就不会起作用。那是你的问题吗?

如果您使用Multiway或 Fourway 组件,您可以这样做:

.bind('Moved', function(from) {
    if(this.hit('mushroomRed')){
        this.attr({x: from.x, y:from.y});
    }
}).

编辑:完整示例

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

var player = Crafty.e("2D, Canvas, Color, player, Multiway, Collision")
   .attr({x: 0, y: 0, w: 50, h: 50})
   .color("rgb(0,255,0)")
   .multiway(3, {UP_ARROW: -90, DOWN_ARROW: 90, RIGHT_ARROW: 0, LEFT_ARROW: 180})
   .bind('Moved', function(from) {
       if(this.hit('mushroomRed')){
           this.attr({x: from.x, y:from.y});
        }
    });

var mushroom = Crafty.e("2D, Canvas, mushroomRed, Color")
    .attr({x: 200, y: 150, z:1, w: 32, h: 32})
    .color("red");

http://jsfiddle.net/PzKVh/运行

这是使用最新版本的 Crafty 0.4.5。有一些重大变化和很多改进,所以我建议你使用这个版本。

另外,请随时在https://groups.google.com/forum/#!forum/craftyjs的论坛中提问,我认为您更有可能在那里找到帮助 :-)

于 2012-02-03T14:08:26.663 回答