Trigonometry for Game Programming: Part 2/2
In this second and final part of the series, you will learn more about sine and cosine and see some other useful ways to put the power of trig to work in your games. 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 2/2
40 mins
Learn Trigonometry for Game Programming!
Welcome back to the Trigonometry for Game Programming series!
In the first part of the series, you learned the basics of trigonometry and experienced for yourself how useful it is for making games. You saw that math doesn’t have to be boring – as long as you have a fun project to apply it to, such as making your own games.
Oh yes, and you built the foundation for a solid little space shooter game!
In this second and final part of the series, you will add missiles, an orbiting asteroid shield and an animated “game over” screen to your game. Along the way, you’ll learn more about sine and cosine and see some other useful ways to put the power of trig to work in your games.
Get ready to ride the sine wave back into space!
Getting Started
This tutorial picks up where you left off in the last part. If you don’t have it already, here is the project with all of the source code up to this point.
As of right now, your game has a spaceship and a rotating cannon, each with health bars. While they may be sworn enemies, neither has the ability to damage the other, unless the spaceship flies right into the cannon.
It’s time for some fireworks. You will now give the player the ability to fire missiles at the cannon by swiping the screen. The spaceship will then launch a missile in the direction of that swipe. For that, you first need to enable touch handling on the layer.
Open the Xcode project and add these instance variables to HelloWorldLayer.m:
@implemenation HelloWorldLayer
{
...
CCSprite *_playerMissileSprite;
CGPoint _touchLocation;
CFTimeInterval _touchTime;
}
Also add these lines at the bottom of the code inside init:
self.touchEnabled = YES;
_playerMissileSprite = [CCSprite spriteWithFile:@"PlayerMissile.png"];
_playerMissileSprite.visible = NO;
[self addChild:_playerMissileSprite];
You initially set the missile sprite to be hidden and only make it visible when the player fires.
Now add the methods to handle the touches, starting with the one that is called whenever the user first puts her finger on the touchscreen:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
_touchLocation = location;
_touchTime = CACurrentMediaTime();
}
This is pretty simple – you store the touch location and the time of the touch in the new instance variables.
The actual work happens in ccTouchesEnded, which you add next:
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (CACurrentMediaTime() - _touchTime < 0.3 && !_playerMissileSprite.visible)
{
UITouch *touch = [touches anyObject];
CGPoint location = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
CGPoint diff = ccpSub(location, _touchLocation);
if (ccpLength(diff) > 4.0f)
{
// TODO: more code here
}
}
}
This determines whether there hasn’t been too much time between starting and ending the swipe, 0.3 seconds at most (otherwise, the missle doesn’t fire). Also, the player can only shoot one missile at a time, so the touch is ignored if a missile is already flying.
The last bit figures out what sort of gesture the user made: was it really a swipe, or just a tap? You only launch missiles on swipes, not taps.
Note: You have done this sort of calculation a couple of times already – subtract two coordinates, then use the Pythagorean Theorem to find the distance between them – but this code looks quite different.
That’s because you’re using one of the handy built-in Cocos2D functions to do the calculation that you used to do by hand for you. I mentioned that these exist in the previous tutorial but you wouldn’t be using them so you could see how things work the long way.
Well, now that you know how things work, why not use these to save time? The built-in Cocos2D functions work on CGPoint structures. If you look at the code, you’ll see ccpLength() is nothing more than the Pythagorean formula you’ve seen before:
It is common in games to combine the x and y values into one type such as CGPoint. Such a value is referred to as a vector, a topic large enough that it deserves its own tutorial.
Note: You have done this sort of calculation a couple of times already – subtract two coordinates, then use the Pythagorean Theorem to find the distance between them – but this code looks quite different.
That’s because you’re using one of the handy built-in Cocos2D functions to do the calculation that you used to do by hand for you. I mentioned that these exist in the previous tutorial but you wouldn’t be using them so you could see how things work the long way.
Well, now that you know how things work, why not use these to save time? The built-in Cocos2D functions work on CGPoint structures. If you look at the code, you’ll see ccpLength() is nothing more than the Pythagorean formula you’ve seen before:
CGFloat ccpLength(const CGPoint v)
{
return sqrtf(v.x*v.x + v.y*v.y);
}
It is common in games to combine the x and y values into one type such as CGPoint. Such a value is referred to as a vector, a topic large enough that it deserves its own tutorial.
CGFloat ccpLength(const CGPoint v)
{
return sqrtf(v.x*v.x + v.y*v.y);
}
There are two ways you could make the missile fly.
The first would be to create new _playerMissileSpeedX and Y instance variables and fill them in with the correct speed values, based on the angle that you’re aiming the missile. Inside update, you would then add this speed to the missile sprite’s position, and check whether the missile flew outside of the visible screen so the player can fire again. This is very similar to how you made the spaceship move in Part 1 of this tutorial.
However, the missile doesn’t need to change course on its way: it always flies in a straight line. So you can take an alternative approach: calculating the destination point when you launch the missile. Then you can set a CCMoveTo action on the missile sprite and let Cocos2D handle the rest. This also saves you from having to check whether the missile has left the visible screen.
I bet you saw this coming: the second approach is exactly what you are going to implement right now, and you will use trig to do it.
To begin, add the following lines to the TODO section in ccTouchesEnded:
float angle = atan2f(diff.y, diff.x);
_playerMissileSprite.rotation = 90.0f - CC_RADIANS_TO_DEGREES(angle);
_playerMissileSprite.position = _playerSprite.position;
_playerMissileSprite.visible = YES;
This is nothing fancy. You calculate the angle, set up the sprite’s rotation and position, and make the missile sprite visible.
Now, however, comes the math. You know the starting position of the missile (which is the position of the player’s ship) and you know the angle (derived from the player’s swipe motion). What you need to calculate now is the destination point of the missile based on these facts.
There are actually four different situations that you need to handle, so let’s first consider the one where the user swiped in a downward motion:
The destination point always lies just outside the screen instead of exactly on the edge of the screen, because it looks better if the missile completely flies out of sight. For this purpose, add a constant at the top HellowWorldLayer.m and call it Margin:
const float Margin = 20.0f;
To find the destination point, you need more than just the angle. Fortunately, if you know that the player is shooting downward, you also know the vertical distance the missile needs to fly. That is simply the starting y-position of the missile, plus the margin. (Remember that the bottom of the screen is y = 0 in Cocos2D.)
Now you have the angle and the adjacent side. To get the destination point, you simply need to calculate the opposite side of the triangle and add it to the starting x-position of the missile.
That sounds like a job for the tan() function – not the arc tangent that you’ve been using up to now, but the normal one:
tan(angle) = opposite / adjacent
Or for your purposes:
opposite = tan(angle) * adjacent
There’s only one snag. The angle that is pictured in the above diagram isn’t really the angle you measured, because the angle you get back from atan2f() is always relative to the 0 degree line of the circle:
Note that in this particular diagram, the adjacent and opposite sides are swapped – it is now the adjacent you’re looking for. So the formula becomes:
adjacent = opposite / tan(angle)
You could probably make this work, but that division makes me cringe. What if tan(angle) happens to be 0? Then you’ll have a division-by-zero on your hands. I’d much rather stick to the first formula, the one that calculates the opposite.
It turns out that this is actually no problem if you remember that beta = (90 – alpha). In other words, if you position yourself in the opposite corner of the triangle and use an angle of (90 – alpha), then you can use that first formula without problems.
Be careful: now that the opposite side points the other way around, you need to subtract it rather than add it to the starting x-position.
Let’s put all this in code. Modify the ccTouchesEnded method to look like the following:
if (ccpLength(diff) > 4.0f)
{
float angle = atan2f(diff.y, diff.x);
_playerMissileSprite.rotation = 90.0f - CC_RADIANS_TO_DEGREES(angle);
_playerMissileSprite.position = _playerSprite.position;
_playerMissileSprite.visible = YES;
float adjacent, opposite;
CGPoint destination;
// 1
angle = M_PI_2 - angle;
adjacent = _playerMissileSprite.position.y + Margin;
opposite = tanf(angle) * adjacent;
destination = ccp(_playerMissileSprite.position.x - opposite, -Margin);
// 2
id action = [CCSequence actions:
[CCMoveTo actionWithDuration:2.0f position:destination],
[CCCallBlock actionWithBlock:^
{
_playerMissileSprite.visible = NO;
}],
nil];
[_playerMissileSprite runAction:action];
[[SimpleAudioEngine sharedEngine] playEffect:@"Shoot.wav"];
}
This does two things:
- It adjusts the angle so you’re looking at it from the other corner. It then calculates the length of the adjacent side, and uses the tangent function to find the length of the opposite side. Finally, it calculates the destination coordinate.
- It creates a sequence of actions, starting with a
CCMoveTo. Once the sprite has reached its destination, theCCCallBlockaction will make the sprite invisible again.
Build and run, and try it out. Move the ship so that it is about halfway centered on the screen and then swipe down. You should see a missile fly along the path that you swiped. Note that you can only fire one missile at a time – the player should have to wait until the previous missile has disappeared from the screen before firing again.
If you try swiping in any other direction, you’ll notice that the missile doesn’t quite fly where you want. That’s because currently you have only handled the situation where the destination point lies below the bottom of the screen. Each of the other screen edges requires slightly different calculations.
Replace the code that calculates the destination point (the “// 1” section) with this:
if (angle <= -M_PI_4 && angle > -3.0f * M_PI_4)
{
// Shoot down
angle = M_PI_2 - angle;
adjacent = _playerMissileSprite.position.y + Margin;
opposite = tanf(angle) * adjacent;
destination = ccp(_playerMissileSprite.position.x - opposite, -Margin);
}
else if (angle > M_PI_4 && angle <= 3.0f * M_PI_4)
{
// Shoot up
angle = M_PI_2 - angle;
adjacent = _winSize.height - _playerMissileSprite.position.y + Margin;
opposite = tanf(angle) * adjacent;
destination = ccp(_playerMissileSprite.position.x + opposite, _winSize.height + Margin);
}
else if (angle <= M_PI_4 && angle > -M_PI_4)
{
// Shoot right
adjacent = _winSize.width - _playerMissileSprite.position.x + Margin;
opposite = tanf(angle) * adjacent;
destination = ccp(_winSize.width + Margin, _playerMissileSprite.position.y + opposite);
}
else // angle > 3.0f * M_PI_4 || angle <= -3.0f * M_PI_4
{
// Shoot left
adjacent = _playerMissileSprite.position.x + Margin;
opposite = tanf(angle) * adjacent;
destination = ccp(-Margin, _playerMissileSprite.position.y - opposite);
}
You have actively divided the screen into four sections, like slices of a pie:
Each of these sections calculates a slightly different destination point. Notice that the code for shooting left comes last, because here you have the issue of switching from +180 to -180 degrees again (recall that this is the range of values that atan2() returns).
Now you should be able to fire in any direction! Build and run and give it a try.
There is still one problem (how could there not be?). Sometimes the missile appears to be going faster than at other times.
That's because currently, the duration of the animation is hard-coded to last 2 seconds. If the missile needs to travel far, then it goes faster in order to cover more distance in the same amount of time.
Instead what you want is for each missile to always travel at the same speed. The hypotenuse comes to the rescue once more!
First, add a new constant at the top of HelloWorldLayer.m:
const float PlayerMissileSpeed = 300.0f;
This is the distance that you want the missile to travel per second. By calculating the length of the hypotenuse, you know the actual distance that the missile travels. To get the needed duration of the animation, you divide those two distances.
Sounds complicated? Nah…
In ccTouchesEnded, change the code that creates the action (the // 2 section) to the following:
float hypotenuse = sqrtf(adjacent*adjacent + opposite*opposite);
ccTime duration = hypotenuse / PlayerMissileSpeed;
id action = [CCSequence actions:
[CCMoveTo actionWithDuration:duration position:destination],
[CCCallBlock actionWithBlock:^
{
_playerMissileSprite.visible = NO;
}],
nil];
That’s all there is to it. Build and run the app again. Now the missile always flies at the same speed, no matter how far or close the destination point is.
And that’s how you use trig to set up a CCMoveTo action. It’s a bit involved, but then it’s largely fire & forget because Cocos2D does all the work of animating for you.








