views:

63

answers:

2

I have my object tracking the mouse using the onmousemove event. But I would like to make it smooth. I'm sure this can't be difficult in jQuery but I'm not finding any really good resources.

One idea I had was to simply use the animate function and calculating the offsets that I want to move to. Then if the mouse moves again before the animation is complete, I would use the stop function to stop the animation. I would recalculate my destination and away I go again. This seems a little hack-ish and I also imagine that it will be a little jerky. I'm sure there has to be a better way. Any Ideas?

EDIT
Sorry I didn't make my problem very clear. I have the object tracking the mouse in real time, so that it moves exactly the same as my mouse. The problem is that I want it to be smooth and lag behind with acceleration effects like Andy Lin mentioned below. I'm just a little lost how to actually implement this.

A: 

when you are using onmousemove, you do not need to have the object change its behavior with every invocation.

e.g. you can add a timer to say that within period of time, the object will not response to mousemove and will follow its original path, and upon timeout or mouse move stop, move according to the destination.

also, you can simulate an acceleration and slow down effect with animation settings.

Andy Lin
You are right on here with what I am looking for. You have given me some ideas but I don't quite see through the implementation.
Icode4food
+1  A: 

I am afraid, that there is no better way, than animate. If you add a smoothing function, then you would simply do the same thing that animate does. Be sure, not to queue your animations or they will look weird. I got nice results with this:

var obj = $('<div style="width:50px;height:50px;background:red;position:absolute"></div>');

obj.appendTo(document.body);

$(document).bind('mousemove',function(ev){
 obj.animate({top:ev.pageY,left:ev.pageX},{queue:false,duration:200,easing:'linear'})});
Baju
That looks like it would come very close to what I am looking for!
Icode4food
What do you miss?
Baju
@Baju: The only thing I am missing is to give it a try and figure out what won't work!
Icode4food
Thanks. If you use jquerui you can also use these settings:{queue:false,duration:300,easing:'easeOutBack'}
Baju