if have div 5x5 square or something. want able click on it, while holding down mouse, move in direction, , upon release of mouse, have div fly towards direction "flicked". how can accomplish jquery or javascript? not sure if algorithm or logic behind this.
from conceptual perspective (i'll beaten actual code no doubt shortly) register mouse coordinates on mousedown, , compare them against mouse coordinates on mouseup determine angle @ move div (this allow div continue moving in correct direction, when mouseup close div).
the easier way move square towards mouseup coordinates (i.e. mouse down coordinates don't matter in small div), doesn't work if mouseup close mousedown.
either way, use answer (how make div or object gradually move point of mouseclick javascript?), except on mouseup/mouserelease instead of click, ideally towards projected point (along line between mousedown , mouseup @ specified distance).
edit
i've included prototype example below (it's rushed , use plenty of optimisations + clearer concept on differences between page/graph y-axis, better handling of steep slopes, calculating distance fling based on distance between mousedown/mouseup fauxtrot mentions in comments, perhaps disabling fling after first fling can keep "flinging around" @ moment, "out of bounds" checks , perhaps reverse bouncing off edges).
running example: http://jsfiddle.net/9b9sa/
html
<div id="bluebox" style="width:100px; height:100px; background-color:blue; position:absolute; left:300px; top:300px;"> </div>
jquery (including jquery ui animate)
var startdownx, startdowny; $(document).ready(function() { /* stop default firefox etc. drag */ $(document).bind("dragstart", function() { return false; }); /* capture start of flings */ $('#bluebox').mousedown(function (event) { startdownx = event.pagex; startdowny = event.pagey; }); /* work out fling direction on end of fling */ $(document).mouseup(function(event){ /* page y-axis different graph */ var rise = -(event.pagey - startdowny); var run = event.pagex - startdownx; var newx = $('#bluebox').position().left; var newy = $('#bluebox').position().top; var distancetofling = 100; if (run == 0 || math.abs(rise/run) > 3) { if (rise > 0) { newy -= distancetofling; } else if (rise < 0) { newy += distancetofling; } } else { if (run > 0) { newx += distancetofling; newy -= (rise/run) * distancetofling; } else { newx -= distancetofling; newy += (rise/run) * distancetofling; } } $('#bluebox').animate({ left: newx, top: newy }, 1000); }); });
Comments
Post a Comment