[SOLVED] Make an object follow another object.

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.
User avatar
MarekkPie
Inner party member
Posts: 587
Joined: Wed Dec 28, 2011 4:48 pm
Contact:

Re: [SOLVED] Make an object follow another object.

Post by MarekkPie »

To add to the above: when you divide by the magnitude of the vector, you are "normalizing" it. Your original vector was

Code: Select all

{ magnitude * direction_of_x, magnitude * direction_of_y }
When you normalize it, you are doing this:

Code: Select all

{ magnitude * direction_of_x / magnitude, magnitude * direction_of_y / magnitude }
Therefore, you just end up with a vector simply pointing at the other object, rather than point and stretching to it. From there, you can add any speed you want, and it will be constant no matter how close you are to the other object.
User avatar
Chroteus
Citizen
Posts: 89
Joined: Wed Mar 20, 2013 7:30 pm

Re: [SOLVED] Make an object follow another object.

Post by Chroteus »

Code: Select all

distance = sqrt(dx*dx+dy*dy)
Oh, I see. We use Pythagoras' Theorem to find out the distance. Thanks a lot. Now it *finally* struck me :nyu:
NathanGaming2005
Prole
Posts: 3
Joined: Wed Jan 02, 2019 1:24 pm

Re: Make an object follow another object.

Post by NathanGaming2005 »

micha wrote: Sat Apr 13, 2013 5:01 pm
Chroteus wrote:

Code: Select all

function fish_move(dt)
	dx = (player.x - fish.x) * (fish.speed * dt)
	dy = (player.y - fish.y) * (fish.speed * dt)
	fish.x = fish.x + (dx * dt)
	fish.y = fish.y + (dy * dt)
end
I'd do it the same way, with two further modification.
First, you put in dt twice. You only need it once for each coordinate. So either remove it in the first two lines or in the second two lines.
Second, you probably noticed, that the fish is faster, if it is further away from the player. This is because, dx and dy both become larger, the larger the distance is.
Maybe this is what you want. If not, here is how to fix it. Divide the distance vector by its length:

Code: Select all

function fish_move(dt)
  dx = player.x - fish.x
  dy = player.y - fish.y
  distance = sqrt(dx*dx+dy*dy)
  fish.x = fish.x + (dx / distance * fish.speed * dt)
  fish.y = fish.y + (dy / distance * fish.speed * dt)
end
the sqrt don't working why?
Post Reply

Who is online

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