1

I'm trying to rotate a rectangle to always point at the mouse position.

I've tried this:

document.getElementById('viewport').onmousemove = function(e){

     var scratch = Physics.scratchpad();
     mousePos = scratch.vector().set(e.x, e.y);

    var newAngle = box.state.pos.angle(mousePos);
    box.state.angular.pos = newAngle;

    scratch.done();
};

Thanks.

Konz
  • 13
  • 2

1 Answers1

1

Maybe try something like this:

document.getElementById('viewport').onmousemove = function(e){

    var scratch = Physics.scratchpad();
    // assuming your viewport is the whole screen
    mousePos = scratch.vector().set(e.pageX, e.pageY); 
    mousePos.vsub( box.state.pos ); // get vector pointing towards mouse pos

    var newAngle = mousePos.angle(); // get angle with respect to x axis
    box.state.angular.pos = newAngle;

    scratch.done();
};
Jasper
  • 1,193
  • 1
  • 9
  • 14
  • Thanks! worked perfectly. Can you explain me why get the angle between the mouse position and the box position does not work, and the angle between the substract of those two vectors and the x axis does? Or can you redirect me to a page to learn about this? – Konz Jun 17 '14 at 21:39
  • Well the `.angular.pos` is always with respect to the x-axis. So you need to get the angle with respect to the x axis. What you were calculating was a different angle. I hope this picture isn't too terrible of an explanation: http://screencast.com/t/lbS7AN8rtWpa – Jasper Jun 20 '14 at 15:59
  • Thanks for this answer. I still don't quite get why the axes in your diagram have (0,0) in the bottom-left instead of the top-left (I thought all the coordinates in PhysicsJS were top-left based?). Also, I needed to add 90 degrees (Math.PI / 2) to the angle you provided in the code example above in order to make it align with the mouse position. Why is that? Thanks! – bartzy May 31 '15 at 11:07