Move towards mouse

flerpyderp

Member
I'm trying to have an object move towards the mouse at a speed of 10, then slow down until it lands exactly at (or at least very close to) the mouse coordinates.

The following code is close, but if the object has stopped, then the mouse is moved again, the object will not move until the distance between them is greater than maxspeed. It would be preferable that if the object is too close to the mouse to use its maxspeed without overshooting, it will calculate its speed based on distance to the mouse and always move to its coordinates.

GML:
var dist = point_distance(x,y,mouse_x,mouse_y);
var dir = point_direction(x,y,mouse_x,mouse_y);
     
var maxspd = 10;

if (dist > maxspd)
{      
    spd = maxspd;
}
else
{
    if (spd > 1) spd *= 0.8;
    else spd = 0;
}  

hspd = lengthdir_x(spd,dir);
vspd = lengthdir_y(spd,dir);

x += hspd;
y += vspd;
Any help is appreciated.
 

Joe Ellis

Member
I think a simple lerp will work exactly how you described:


GML:
x = lerp(x, mouse_x, 0.2)
y = lerp(y, mouse_y, 0.2)
Edit- Haha, just seen you remembered lerp. Good old lerp.
 
Top