Prevent object clipping in craftyJS
-
22-04-2021 - |
Question
In CraftyJS, how do i stop my player entity from clipping into other entities?
This is my object:
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});
and this is my player onHit:
.onhit("mushroomRed", function() {
this.x += this._speed;
this.stop();
}
It works only when i approach it from certain angle, otherwise, it goes haywire.
Advice?
Solution
It looks like you are using
this.x += this._speed;
to move the player away from the mushroom after they have collided. But as you are only moving it in the x direction it wont work if you collide from top or bottom. Is that your problem?
If you use the Multiway or Fourway components you could do this instead:
.bind('Moved', function(from) {
if(this.hit('mushroomRed')){
this.attr({x: from.x, y:from.y});
}
}).
Edit: complete example
// 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");
Running at http://jsfiddle.net/PzKVh/
This is using the latest version of Crafty 0.4.5. There has been a few breaking changes and a lot of improvements, so i would suggest you use this version.
Also, feel free to ask in the forums at https://groups.google.com/forum/#!forum/craftyjs I think you are much more likely to find help there :-)