Zakukashi
Zakukashi

Reputation: 586

jquery trying to achieve mouse direction & angle

Im trying to do a mouse direction + angle script just like the game "Pixel". I want to be able to move the element around with my mousemove event and have the element feel the direction and point its tip towards it. I cant seem to understand how the method works, I tried several different approaches to figure out the direction of the mouse movement to an angle but none worked. Here is an example of the game, of course its in flash but the method should be possible in jquery. http://www.agame.com/game/pixel.html

if anyone every came across a jfiddle for this or knows a good approach let me know.

EDIT*

I tried this below and it almost works but only when the direction of the mouse is moved left and right. Up and down seems to be in-versed and flipped

var follow = $(".you");
var xp = 0, yp = 0;
var loop = setInterval(function(){
xp += (mouseX - xp) / 5;
yp += (mouseY - yp) / 5;
follow.css({left:xp, top:yp});

}, 15);
var lastx = 0;
var lasty = 0;
var img = $('.you');
var offset = img.offset();
function mouse(evt){

var mouse_x = evt.pageX; var mouse_y = evt.pageY;
    var degree=getDirection(lastx,lasty,mouse_x,mouse_y);
     lastx=mouse_x;
     lasty=mouse_y;
   img.css('-moz-transform', 'rotate('+degree+'deg)');
    img.css('-webkit-transform', 'rotate('+degree+'deg)');
    img.css('-o-transform', 'rotate('+degree+'deg)');
    img.css('-ms-transform', 'rotate('+degree+'deg)');
   }
   $(".field").mousemove(mouse);


 function getDirection(x1, y1, x2, y2,ns)
{
var dx = x2 - x1;
var dy = y2 - y1;
return (Math.atan2(dx,  dy) / Math.PI * 180);
}

Upvotes: 1

Views: 2629

Answers (2)

toto2
toto2

Reputation: 5326

In one of your comment, you say you use top/left, but that is clearly insufficient: it will move your image, but do nothing to the angle.

You'll have to use CSS style transform: rotate(45deg). Look here. Unfortunately, transform being relatively new, you'll actually have to add a CSS line for each browser type: -ms-transform: rotate(45deg), -webkit-transform: rotate(45deg), etc. You can also use rad instead of degrees, which is what Math.atan returns.

Look here too, where they suggest a rotation plug-in that simplifies things.

Upvotes: 0

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25465

This is how you could find the direction of travel

function getDirection(x1, y1, x2, y2)
{
    var dx = x2 - x1;
    var dy = y2 - y1;

    return Math.atan2(dx,  dy) / Math.PI * 180;​
}

I'm not quite sure how you're drawing the image so can't help you implement it.

Upvotes: 2

Related Questions