Page 1 of 1

Moving sprite toward mouse

Posted: Sun Jan 02, 2011 12:20 am
by danlthemanl
I'm not quite sure how to do this. I've tried all I can and nothing seems to work. It must be some kind of math that I am not familiar with?

Re: Moving sprite toward mouse

Posted: Sun Jan 02, 2011 12:52 am
by TechnoCat
danlthemanl wrote:I'm not quite sure how to do this. I've tried all I can and nothing seems to work. It must be some kind of math that I am not familiar with?
If you split it into X and Y then it becomes very easy algebra. Just test and move accordingly.

However, if you want a constant speed, you will need to use some linear algebra. Finding the x and y component from mouse to sprite and then getting the normalized vector of that.

Re: Moving sprite toward mouse

Posted: Sun Jan 02, 2011 1:13 am
by Robin
In pseudocode:

Code: Select all

image.x = image.x + difference between mouse_x and image.x times a factor < 1
image.y = image.y + difference between mouse_y and image.y times a factor < 1

Re: Moving sprite toward mouse

Posted: Sun Jan 02, 2011 1:43 am
by danlthemanl
I'm still not getting it. Whatever I do the sprite always moves in an angle, i can't get it to move toward the mouse!

this is what i have:

Code: Select all

	-- In load
	PlayerX = 400
	PlayerY = 300
	PlayerVel = -0.2
	
	if love.mouse.isDown("l") then
		mouseX = love.mouse.getPosition(x)
		mouseY = love.mouse.getPosition(y)
		diffX = PlayerX / mouseX - 1
		diffY = PlayerY / mouseY - 1
		
		PlayerX = PlayerX + diffX * PlayerVel
		PlayerY = PlayerY + diffY * PlayerVel
	end
and it just moves at an angle.

Re: Moving sprite toward mouse

Posted: Sun Jan 02, 2011 2:11 am
by tentus
Change

Code: Select all

		mouseX = love.mouse.getPosition(x)
		mouseY = love.mouse.getPosition(y)
to

Code: Select all

mouseX,mouseY = love.mouse.getPosition()
love.mouse.getPosition() returns to values in a specific order, you can't tell it to give you a single value.

Re: Moving sprite toward mouse

Posted: Sun Jan 02, 2011 2:24 am
by TechnoCat