Make an object follow the mouse pointer with LÖVE2D

I've been trying to make a picture follow the mouse pointer with LÖVE2D.

I want that the object follow the mouse, and not just be the mouse coordinates, I did that. So I toked the distance between the objects:

distance = dist(object.x, mouseX, object.y, mouseY)

the dist definition is the one from analytic geometry(Distance between two points in the Cartesian plan), well, now I don't know what to do, I tried a timer to update the object's coordinates but didn't work out.

if object.timer >= 2 then
--object.x = mouseX
--object.y = mouseY
object.x = mouseX - distance
object.y = mouseY - distance
object.timer = 0
end

It didn't work out either :(. Well, I tried some other stuff, like whale.x - distance, but didn't worked out either, how can I make the object follow the mouse, like, if I let my mouse on (500, 300(Screen coordinates) the image would follow until it reaches the position desired which is the mouse position.

And yea, I really need to learn more math. >.>

Yeah, vector geometry really helps when thinking about positions of things. It might be helpful to read over that page for a refresher.

To find the vector from your object to the mouse position, subtract the object position from the mouse position:

local objectToMouse = {
x = mousex - object.x,
y = mouseY - object.y
}

Then you can add some fraction of that vector to your object's position:

local fraction = 1 / 10
object.x = object.x + (objectToMouse.x * fraction)
object.y = object.y + (objectToMouse.y * fraction)

You can put those in your love.update to make them happen every step. Then every step the object will move one tenth of the distance to the mouse position.

It looks like this for me if I render a circle at the object's position: If you find yourself using a lot of vectors, there's a really good vector class in vrld's HUMP library that might simplify your code by letting you do the common vector operations with less code.

• Uow, nice explanation, I gonna try your implementation and return here to mark as correct, thank you to pointing vector geometry, I've never heard about it hahaha, but I already done this kinda of sum, subtraction in vectors. – Rafael Campos Nunes Jun 15 '14 at 21:26