Fabienne Moreau
Fabienne Moreau

Reputation: 11

How to work with multiple hitbox areas in crafty.js?

I am trying to create multiple hitbox areas in my game, but I can't find any documentation or examples of how to work with them. The scenario is, my "Hero" have 2 hitbox, one on his feet and another on his body. If he hits an enemy with the foot hitbox, the enemy dies. If he hits the enemy with his body, his health have to be decreased. How can I identify which hitbox create the collision event?

Upvotes: 1

Views: 324

Answers (1)

mucaho
mucaho

Reputation: 2169

The answer to this question is similar to one recently answered on Crafty's forum.

You can attach invisible entities to a parent entity, which will move alongside the parent entity and simultaneously serve as hitboxes for your parent entity. In response to detecting collisions on these child entities, you can inform the parent entity about those collisions. There may be other ways to achieve the same thing.

Following is a small example that showcases the principle.
Use WASD to move, observe the color change depending on which body part touches the brown enemy.
Note that it doesn't resolve the case when both body parts are colliding with the enemy. Triggering events on the parent entity was reduced to directly modifying the parent entity for simplicity. onHit has its limitations and is used here for simplicity.

Crafty.init();

var hero = Crafty
       .e("2D, DOM, Color, hero, Fourway")
       .attr({x: 0, y: 0, w: 64, h: 128})
       .color('gray')
       .fourway();

var body = Crafty
       .e("2D, Collision, WiredHitBox, body")
       .attr({x: 0, y: 0, w: 64, h: 96})
       .onHit('enemy', function() {
         this._parent.color('red');
        }, function() {
         this._parent.color('gray');
        });

var feet = Crafty
       .e("2D, Collision, WiredHitBox, feet")
       .attr({x:0, y: 96, w: 64, h: 32})
       .onHit('enemy', function() {
         this._parent.color('green');
        }, function() {
         this._parent.color('gray');
        });

hero.attach(body);
hero.attach(feet);

Crafty.e("2D, DOM, Color, enemy")
      .attr({x: 150, y: 96, w: 32, h: 32})
      .color('brown');
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty-min.js"></script>

Upvotes: 1

Related Questions