Rotate entity to view mouse (Craftyjs)

240 Views Asked by At

I've been trying to get my player entity to rotate to the mouse however I cannot get the MouseMove event to trigger.

Crafty.e("2D, Mouse, Canvas, Color"
   .attr({ w:1000, h:1000, x:0, y:0 })
   .bind('MouseMove', function(e)
   {
         console.log("Mouse Pos:"+ e.x +","+e.y);
        //get hero
         var pos1 = {
           x: e.x,
           y: e.y
         }
         var pos2 = {
           x: player.x,
           y: player.y
         }
         player.rotation = 0;
         player.rotation = -Engine.degree(pos1, pos2);


     })

When I replace MouseMove with click or mousedown or any other mouse event, it rotates to the mouse when that event occurs. However it never calls the mousemove function. What am I doing wrong?

1

There are 1 best solutions below

0
mucaho On

Have a look at CraftyMouseFace, a Crafty component made by the community:

This component does the following:

  • It finds the angle between given Sprite and mouse position and triggers a Crafty event which holds information about current mouse position and calculated angle in radians and degrees.
  • Determines sprite facing direction.
  • Triggers Crafty events when a mouse buttons is pressed down or released up anywhere on the game screen.

The first feature sounds like what you need.

Let's put the MouseMoved event and its event data to test in the following snippet.
Move the mouse pointer around and notice how the green rectangle rotates to face the pointer.

Crafty.init();

Crafty.e("2D, DOM, Color, MouseFace")
    .attr({x: 75, y: 75, w: 60, h: 60})
    .origin("center")
    .color('green')
    .bind("MouseMoved", function(data) {
        this.rotation = data.rad * 180 / Math.PI;
    });
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty-min.js"></script>
<script src="https://cdn.rawgit.com/petarov/CraftyMouseFace/master/src/craftyMFace.js"></script>