0
 player.bind('Move', function(from) {


                                    if(this.hit('Tree')){

                                        player.x = from._x
                                        player.y = from._y
             // Here player.x and player.y have right value but not renderered here.

                                    }
                }
                )

I debugged that program enters here and from._x and from._y have good values. But player remains "behind" the Tree.

Alice
  • 77
  • 3
  • 4
  • The previous position before a Collision in Crafty.Js could be the nearest position before touching the other entity. Instead of trying to go back to some previous position, create a callback that makes your entity go back some space (you'll have to check the direction where your entity is looking at). – xale94 May 31 '19 at 06:25

1 Answers1

0

I'm don't have a lot of CraftyJS experience yet, so don't take this as the best way to do it, but...

Some references I found in the API documentation:

  • Apply the Collision component to the player and tree
  • use onHit() for the player. When fired, this is passed a collection of hitDatas. Found definition of hitData in the description for hit()

Here's an example -- when the entity tagged with "Player" component collides with any component tagged "Tree", will back the player object's x position off by the amount it is overlapping with the tree.

<html>
<body>
    <div id="game"></div>
    <script type="text/javascript" src="https://rawgithub.com/craftyjs/Crafty/release/dist/crafty-min.js"></script>
    <script>
      Crafty.init(640,100, document.getElementById('game'));


      Crafty.e('2D, Canvas, Color, Twoway, Player, Collision')
       .attr({x: 0, y: 50, w: 50, h: 50})
       .color('#00F')
       .twoway(400)
       .onHit('Tree', function(hitDatas) {
        hitData = hitDatas[0];

        this.x -= hitData.overlap * hitData.nx;
       });

      Crafty.e('2D, Canvas, Color, Tree, Collision')
       .attr({x: 300, y:0, w: 40, h: 100})
       .color('#873');

    </script>
  </body>
</html>