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?
2 Answers
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].
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.
-
\$\begingroup\$ can you explain the mathematics more? \$\endgroup\$ Commented 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\$ Commented Jul 28, 2012 at 23:57
-
\$\begingroup\$ yes why we use cos and sin instead of xpos+=velx \$\endgroup\$ Commented 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\$ Commented Jul 29, 2012 at 0:02
-
\$\begingroup\$ So the velocity is analyzed in two dimensions, but what do you mean by optimal speed ? \$\endgroup\$ Commented Jul 29, 2012 at 0:14