javascript - Rotating object to face mouse pointer on mousemove -


i've got mousemove cursor in game make object shoot towards mouse cursor. i'd object rotate along in line mousecursor. how can convert x , y of cursor degree angle rotate object to?

i hope fiddle make things little clearer of mean rotating player(black block): http://jsfiddle.net/3neuv/4/

here's mousemove function now; making sure cursor remains in it's bounding box

function mousemove(e) {     if (cursor) {         if (e.rawx && e.rawy) {             cursorboundingbox(e.rawx, e.rawy);         }     } } 

basically need find vector between the point in center of box, , point of mouse cursor, calculate angle , convert degrees. apply angle via css:

var box=$(".box"); var boxcenter=[box.offset().left+box.width()/2, box.offset().top+box.height()/2];  var angle = math.atan2(e.pagex - boxcenter[0], - (e.pagey - boxcenter[1]) )*(180/math.pi);        box.css({ "-webkit-transform": 'rotate(' + angle + 'deg)'});     box.css({ '-moz-transform': 'rotate(' + angle + 'deg)'}); 

what

ok, let's take apart. have:

enter image description here

the vector ab goes between center of box , mouse position. went calculate Θ (theta), angle between x axis , ab. since ab creates triangle x , y axes, can use arctan function calculate it. more precisely, use convenience function of arctan2 gives positive angle when y>0 , negative angle when y<0.

atan2 returns degrees in radians, , css works degrees, convert between 2 using 180/math.pi. (a radian measure of angle that, when drawn central angle of circle, intercepts arc length equal length of radius of circle. - taken here )

one last caveat - since in browser y axis inverted (meaning, further down go in page, higher y value gets), had flip y axis: did adding minus sign on y term:

- (e.pagey - boxcenter[1])

i hope helps clear things...

here's isolated jsfiddle example

btw, game hard! :)


Comments