Page 2 of 2
Re: [SOLVED] Make an object follow another object.
Posted: Sat Apr 13, 2013 5:10 pm
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.
Re: [SOLVED] Make an object follow another object.
Posted: Sat Apr 13, 2013 8:11 pm
by Chroteus
Oh, I see. We use Pythagoras' Theorem to find out the distance. Thanks a lot. Now it *finally* struck me
Re: Make an object follow another object.
Posted: Fri Jan 04, 2019 11:50 am
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?