1
\$\begingroup\$

I have read source code of asteroids game. I want to know why when updating the ship's position in X, and Y Axis, we must write it in sin and cosine of the current angle. Is it angular velocity ? why we can't use linear velocity and update the position by a linear velocity?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Look at the unit circle below, [cos(t), sin(t)] simply gives you a 2D unit vector for an angle of t. For any direction between 0 and 2PI (0* and 360*) just feed cos/sin the correct angle. Want to go west? Use t=PI radians (or 180* degrees), this gives you the unit vector [cos(PI), sin(PI] or [-1,0].

unit circle

\$\endgroup\$
1
\$\begingroup\$

Think of it as shooting a cannon.

When you shoot a cannon parallel with the ground with a given force, it is guaranteed to go horizontally and not vertically. This is because we apply force in this direction. However, if we were to apply a linear velocity to both the 'X' and 'Y' components, this would create a constant speed which would look silly.

For Asteroids, you want to make sure a force is applied in the right direction. Otherwise, what would happen is your asteroid was pointing directly east or west? Would you still want it to move at the same direction each time? While pushing Right, you want the computed magnitudes of each components velocity to be correct.

\$\endgroup\$
6
  • \$\begingroup\$ can you explain the mathematics more? \$\endgroup\$ Jul 28, 2012 at 23:54
  • \$\begingroup\$ You want to know more about why we use Cos and Sin or my answer to flesh it out? \$\endgroup\$ Jul 28, 2012 at 23:57
  • \$\begingroup\$ yes why we use cos and sin instead of xpos+=velx \$\endgroup\$ Jul 28, 2012 at 23:59
  • \$\begingroup\$ OK. Let us assume your ship is facing completely to the right. Tip is to the right. Your angle is 0. You want no vertical velocity here, only horizontal. Your velocity is computed via: x = cos(theta) * magnitude y = sin(theta) * magnitude We know sin(0) = 0. This means we will have a 'y' velocity of 0. However, we know doing cos(0) = 1. This means 1 * magnitude = maximum speed in the x direction. Moving directly at 0 degrees would give you the optimal speed! Similarly, if you have an angle of 90 degrees, the sin of 90 degrees is now 1. Maximum y. Cos 90 is now 0. No x. \$\endgroup\$ Jul 29, 2012 at 0:02
  • \$\begingroup\$ So the velocity is analyzed in two dimensions, but what do you mean by optimal speed ? \$\endgroup\$ Jul 29, 2012 at 0:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .