javascript - JS - push ball at an angle -
i want push ball @ angle using mouse.
to this, far have:
- calculated mouse movement angle
- calculated original , new positions of ball
but ball isn't moving when hit ball. seems trail behind.
- i think due animating in callback. need run animation there in order pass in newx , newy after calculation.
and goes off on weird angles.
- i think because when set newx, newy, it's adding new location, instead of positioning should be?
- or, noticed angles don't follow way around circle (meaning, moving upper right quadrant gives angle range of 0 - 90, moving lower right gives range of 0 - 90 still.. should give range of 270 - 360). not sure how fix this.
lastly, angle gives nan. not sure why it's not number
any thoughts?
fiddle: http://jsfiddle.net/edh59/
code:
//get angle of mouse movement function getangle (x1, y1, x2, y2) { var dy = math.abs(y2-y1); //opposite var dx = math.abs(x2-x1); //adjacent var dist = math.sqrt((dy*dy)+(dx*dx)); //hypotenuse var sin = dy/dist; //opposite on hypotenuse var radians = math.asin(sin); var degrees = radians*(180/math.pi); //convert radians degrees angle = degrees; return degrees; //return angle in degrees } $("canvas").mousemove(function(e) { getdirection(e); if (!set) { x1 = e.pagex, y1 = e.pagey, set = true; } cleartimeout(thread); thread = settimeout(callback.bind(this, e), 100); }); $(".anotherbox").mouseenter(function(e) { pos = $(this).position(); box2x = pos.left; box2y = pos.top; if(animate) { $(this).animate({ top : newy+"px", left: newx+"px", }, "slow"); } animate = false; }); } function calcnewloc (x, y, xdist, ydist) { newx = x + (xdist * math.cos(angle)); newy = y + (ydist * math.sin(angle)); } function callback(e) { x2 = e.pagex; y2 = e.pagey; t2 = new date().gettime(); var xdist = x2 - x1, ydist = y2 - y1, time = t2 - t1; //to calc angle... need starting position , ending position $(".angle").html(getangle(x1, y1, x2, y2)); calcnewloc(x1, y1, xdist, ydist); animate = true; //only allow animation of ball once new locations calculated log("mouse has stopped"); set = false; }
to have angle, have store previous location of mouse , consider current angle angle between last measure , current. kind of averageing on smooth result. in demo current direction drawn in red if direction vector long enough.
the computation of angle done classical atan2.
var mouseangle = math.atan2(my-lastmy, mx-lastmx);
you can have @ result here : http://jsfiddle.net/gamealchemist/z3u8g/4/embedded/result/
code here : http://jsfiddle.net/gamealchemist/z3u8g/4/
Comments
Post a Comment