0

I'm trying to understand Crafty. Here's my code.

Crafty.init(500,300, document.getElementById('game'));

Crafty.e('Floor, 2D, Canvas, Color')
  .attr({x: 0, y: 250, w: 200, h: 10})
  .color('green');

Crafty.e('SecondFloor, 2D, Canvas, Color')
  .attr({x: 250, y: 230, w: 200, h: 10})
  .color('red')

Crafty.background('#FFFFFF url(http://samenvattingleren.nl/img/img2.jpg) no-repeat center center');

Crafty.e('2D, Canvas, Color, Fourway, Gravity')
  .attr({x: 25, y: 5, w: 50, h: 50})
  .color('orange')
  .fourway(4)
  .gravity("Floor")
  .bind('KeyDown', function(e) {
    if(e.key == Crafty.keys.LEFT_ARROW) {
    this.x = this.x - 1;
    } else if (e.key == Crafty.keys.RIGHT_ARROW) {
        this.x = this.x + 1;
    } else if (e.key == Crafty.keys.UP_ARROW) {
    this.y = this.y - 1;
    } else if (e.key == Crafty.keys.DOWN_ARROW) {
    this.y = this.y + 1;
    } else if (e.key == Crafty.keys.ESC) {
        this.x = 0;
    }
  })

I want to add

Crafty.e('2D, Canvas, Color, Fourway, Gravity')
      .attr({x: 25, y: 5, w: 50, h: 50})
      .color('orange')
      .fourway(4)
      .gravity("Floor")
      .gravity("SecondFloor") //This is what i want to add

But this doesnt work. The square still goes trough SecondFloor

TZHX
  • 5,291
  • 15
  • 47
  • 56
Mees Maas
  • 29
  • 1
  • 1
  • 7

1 Answers1

1

The "Floor" component should be thought of as a kind of tag, which you'll add to any entity that should act as a floor. In your example code, there doesn't seem to be any need to distinguish between "Floor" and "SecondFloor", so you could just change the latter to "Floor".

If you have two custom components which you want to always act as a floor, the solution is to have them require the "Floor" component automatically. For instance

Crafty.c("IcePlatform", {
    init: function(){ this.requires("Floor"); }
    // Stuff specific to "IcePlatform"
};

Crafty.c("MovingPlatform", {
    init: function(){ this.requires("Floor"); }
    // Stuff specific to "MovingPlatform"
};

Then whenever any entity which has "MovingPlatform" or "IcePlatform" will also act as a "Floor", and interact appropriately with Gravity.

starwed
  • 2,536
  • 2
  • 25
  • 39