0
\$\begingroup\$

I will try to explain it as well as I can excuse me if I'll fail. I have the following simple game situation: game situation

I know the coordinates of each point. So each of the green points try to hit the blue one. I know the target of each green point. What I would like is to acquire a nice movement effect so that lets say each green point will change the coordinates in 3 steps before getting to the target. For example: if a point would be at (2,2) and the target is at (8,9) it would change to (3,3), then (6,7) then (8,9). The idea is how to aceive this? Is there some math involved with sin and cos? I don't know if choosing a random number for example between (2,8) and (2,9) for the new x and y coordinates will do it. I don't know if so it follows the correct direction of the point towards the target. I use pygame, but if you don't know pygame but can help me with how to aceive this effect is cool. Thanks a lot!

\$\endgroup\$
1
  • \$\begingroup\$ surely this is a simple path finding situation? each update cycle figure out where youre green dots are and move them x amount closer to the blue dot ... whatever the current position is for each is simply updated? ... am i missing something here? \$\endgroup\$ – War Oct 10 '14 at 10:02
1
\$\begingroup\$

I don't think you need sin/cos. This is simple vector math. A vector is calculated by subtracting a point from another, as in target minus the source.

In your case, the vector from (2,2) to (8,9) would be (8-2,9-2) = (6,7). Now you can always recover the target by adding the vector to the source (6,7)+(2,2)=(8,9).

If what you want is to have 3 steps, just divide the vector by 3 and add that to the source. After you add it three times you'll be at the target, and you'll stay in the line that connects source and target. In your example, each step would be (2,2.33) and your intermediate points would be (4,4.33) and (6,6.66).

More generally, you can "normalize" the vector, by calculating the length and dividing by it. The length of a vector is:

length = sqrt(v.x*v.x + v.y*v.y)
normal.x = v.x / length
normal.y = v.y / length

Interestingly, this also gives you the distance between source and target. Once you have a normal vector, you can use it to move as much or as little as you want while staying in the line that connects source and target. Just multiply it by that amount and add it to the source.

If you think about it, multiplying by the distance will actually give you the target back. Multiplying by a third of the distance will have the same effect as dividing the vector by three, as we did before.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks a lot! You just saved my code :). Works perfectly! \$\endgroup\$ – user3009269 Oct 10 '14 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.