Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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

share|improve this answer
add comment

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.

share|improve this answer
    
can you explain the mathematics more? –  Ahmed Saleh Jul 28 '12 at 23:54
    
You want to know more about why we use Cos and Sin or my answer to flesh it out? –  Vaughan Hilts Jul 28 '12 at 23:57
    
yes why we use cos and sin instead of xpos+=velx –  Ahmed Saleh Jul 28 '12 at 23:59
    
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. –  Vaughan Hilts Jul 29 '12 at 0:02
    
So the velocity is analyzed in two dimensions, but what do you mean by optimal speed ? –  Ahmed Saleh Jul 29 '12 at 0:14
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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