Trigonometry for Game Programming: Part 1/2
Learn Trigonometry for Game Programming in this 2-part tutorial series, where you’ll learn the theory and then practice by making a space shooter game! By Matthijs Hollemans.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Trigonometry for Game Programming: Part 1/2
65 mins
Bouncing Off the Walls
You have a spaceship that you can move using the accelerometers and you’re using trig to make sure it points in the direction it’s flying. That’s a good start.
Unfortunately, having the spaceship get stuck on the edges of the screen isn’t very satisfying. You’re going to fix that by making it bounce off the screen borders instead.
First, comment these lines from updatePlayer:
//newX = MIN(_winSize.width, MAX(newX, 0));
//newY = MIN(_winSize.height, MAX(newY, 0));
Then add the following code to updatePlayer, just after the commented lines:
BOOL collidedWithVerticalBorder = NO;
BOOL collidedWithHorizontalBorder = NO;
if (newX < 0.0f)
{
newX = 0.0f;
collidedWithVerticalBorder = YES;
}
else if (newX > _winSize.width)
{
newX = _winSize.width;
collidedWithVerticalBorder = YES;
}
if (newY < 0.0f)
{
newY = 0.0f;
collidedWithHorizontalBorder = YES;
}
else if (newY > _winSize.height)
{
newY = _winSize.height;
collidedWithHorizontalBorder = YES;
}
This checks whether the spaceship hit any of the screen borders and if so, sets a BOOL variable to YES. But what to do after such a collision takes place? To make the spaceship bounce off the border, you can simply reverse its speed and acceleration.
First, define a constant at the top of the file, above the @implementation line:
const float BorderCollisionDamping = 0.4f;
Add the following lines in updatePlayer, directly below the code you last added there:
if (collidedWithVerticalBorder)
{
_playerAccelX = -_playerAccelX * BorderCollisionDamping;
_playerSpeedX = -_playerSpeedX * BorderCollisionDamping;
_playerAccelY = _playerAccelY * BorderCollisionDamping;
_playerSpeedY = _playerSpeedY * BorderCollisionDamping;
}
if (collidedWithHorizontalBorder)
{
_playerAccelX = _playerAccelX * BorderCollisionDamping;
_playerSpeedX = _playerSpeedX * BorderCollisionDamping;
_playerAccelY = -_playerAccelY * BorderCollisionDamping;
_playerSpeedY = -_playerSpeedY * BorderCollisionDamping;
}
If a collision registered, you flip the acceleration and speed values around. Notice that this also multiplies the acceleration and speed by a damping value, BorderCollisionDamping.
As usually happens in a collision, some of the movement energy is dissipated by the impact. In this case, you make the spaceship retain only 40% of its speed after bumping into the screen edges.
Try it out. Smash the spaceship into the border and see what happens. Who said spaceships can’t bounce?
For fun, play with the value of BorderCollisionDamping to see the effect of different values for this constant. If you make it larger than 1.0f, the spaceship actually gains energy from the collision.
Note: Now why is there an f behind those numbers in the code: 0.4f, 0.1f, 0.0f, and so on? And why did you use atan2f() instead of just atan2()? When you write games, you want to work with floating point numbers as much as possible because, unlike integers, they allow for digits behind the decimal point. This allows you to be much more precise.
There are two types of floating point numbers: floats and doubles (there is also a “long double”, but that’s the same as a double on the iPhone). Doubles are more precise than floats but they also take up more memory and are slower in practice. When you don’t put the f behind the number and just use 0.4, 0.1, 0.0, or when you use the version of a math function without the f suffix, you are working with doubles and not floats.
It doesn’t really matter if you use a double here and there. For example, the time value that CACurrentMediaTime() returns is a double. However, if you’re doing hundreds of thousands of calculations every frame, you will notice the difference. I did a quick test on a couple of my devices and the same calculations using doubles were 1.5 to 2 times slower. So it’s a good habit to stick to regular floats where you can.
Note: Now why is there an f behind those numbers in the code: 0.4f, 0.1f, 0.0f, and so on? And why did you use atan2f() instead of just atan2()? When you write games, you want to work with floating point numbers as much as possible because, unlike integers, they allow for digits behind the decimal point. This allows you to be much more precise.
There are two types of floating point numbers: floats and doubles (there is also a “long double”, but that’s the same as a double on the iPhone). Doubles are more precise than floats but they also take up more memory and are slower in practice. When you don’t put the f behind the number and just use 0.4, 0.1, 0.0, or when you use the version of a math function without the f suffix, you are working with doubles and not floats.
It doesn’t really matter if you use a double here and there. For example, the time value that CACurrentMediaTime() returns is a double. However, if you’re doing hundreds of thousands of calculations every frame, you will notice the difference. I did a quick test on a couple of my devices and the same calculations using doubles were 1.5 to 2 times slower. So it’s a good habit to stick to regular floats where you can.
You may have noticed a slight problem. Keep the spaceship aimed at the bottom of the screen so that it continues smashing into the border over and over, and you’ll see a constant flicker between the up and down angles.
Using the arc tangent to find the angle between a pair of x- and y-components works quite well, but only if those x and y values are fairly large. In this case, the damping factor has reduced the speed to almost zero. When you apply atan2f() to very small values, even a tiny change in these values can result in a big change in the resulting angle.
One way to fix this is to not change the angle when the speed is very slow. That sounds like an excellent reason to give a call to our old friend, Pythagoras.
Right now you don’t have such a thing as “the ship’s speed”. Instead, you have two speeds: one in the x-direction and one in the y-direction. But in order to draw any conclusions about “the ship’s speed” – is it too slow to actually rotate the ship? – you need to combine these x and y speed values into one single value:
Here you are in the Know 2 Sides, Need Remaining Side case discussed earlier.
As you can see, the true speed of the spaceship, that is, how many points it moves across the screen in a second, is the hypotenuse of the triangle that is formed by the speed in the x-direction and the speed in the y-direction. Put in terms of the Pythagorean formula:
true speed2 = _playerSpeedX2 + _playerSpeedY2
To find the actual value, you need to take the square root:
true speed = √(_playerSpeedX2 + _playerSpeedY2)
Add this code to updatePlayer. First remove this block of code:
float angle = atan2f(_playerSpeedY, _playerSpeedX);
_playerSprite.rotation = 90.0f - CC_RADIANS_TO_DEGREES(angle);
And replace it with this block of code:
float speed = sqrtf(_playerSpeedX*_playerSpeedX + _playerSpeedY*_playerSpeedY);
if (speed > 40.0f)
{
float angle = atan2f(_playerSpeedY, _playerSpeedX);
_playerSprite.rotation = 90.0f - CC_RADIANS_TO_DEGREES(angle);
}
Build and run. You’ll see the spaceship now acts a lot more stable at the edges of the screen. If you’re wondering where the value 40.0f came from, the answer is: experimentation. I put some NSLog() statements into the code to look at the speeds at which the craft typically hit the borders, and then I tweaked this value until it felt right.


