Moving sprite toward mouse

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
danlthemanl
Prole
Posts: 11
Joined: Fri Jun 04, 2010 1:11 am

Moving sprite toward mouse

Post 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?
User avatar
TechnoCat
Inner party member
Posts: 1611
Joined: Thu Jul 30, 2009 12:31 am
Location: Milwaukee, WI
Contact:

Re: Moving sprite toward mouse

Post 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.
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Moving sprite toward mouse

Post 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
Help us help you: attach a .love.
danlthemanl
Prole
Posts: 11
Joined: Fri Jun 04, 2010 1:11 am

Re: Moving sprite toward mouse

Post 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.
User avatar
tentus
Inner party member
Posts: 1060
Joined: Sun Oct 31, 2010 7:56 pm
Location: Appalachia
Contact:

Re: Moving sprite toward mouse

Post 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.
Kurosuke needs beta testers
User avatar
TechnoCat
Inner party member
Posts: 1611
Joined: Thu Jul 30, 2009 12:31 am
Location: Milwaukee, WI
Contact:

Re: Moving sprite toward mouse

Post by TechnoCat »

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 2 guests