Trigonometry for Game Programming [Sprite Kit Version]: Part 2/2
Learn about trigonometry functions like sin, cos, and tan while you make a fun iOS space game! By Tony Dahbura.
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 [Sprite Kit Version]: Part 2/2
40 mins
Learn Trigonometry for Game Programming!
Update Note: Check out the updated version of this trigonometry tutorial, now powered by Swift and running on iOS 8!
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 MyScene.m:
@implemenation MyScene
{
...
SKSpriteNode *_playerMissileSprite;
CGPoint _touchLocation;
CFTimeInterval _touchTime;
}
Also add these lines at the bottom of the code inside initWithSize:
_playerMissileSprite = [SKSpriteNode spriteNodeWithImageNamed:@"PlayerMissile"];
_playerMissileSprite.hidden = YES;
[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)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
_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 touchesEnded, which you add next:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (CACurrentMediaTime() - _touchTime < 0.3 && _playerMissileSprite.hidden)
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
CGPoint diff = CGPointMake(location.x - _touchLocation.x, location.y - _touchLocation.y);
float diffLength = sqrtf(diff.x*diff.x + diff.y*diff.y);
if (diffLength > 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.
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.
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.
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 moveTo action on the missile sprite and let Sprite Kit 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 touchesEnded:
float angle = atan2f(diff.y, diff.x);
_playerMissileSprite.zRotation = angle - SK_DEGREES_TO_RADIANS(90.0f);
_playerMissileSprite.position = _playerSprite.position;
_playerMissileSprite.hidden = NO;
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 of MyScene.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 Sprite Kit.)
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 touchesEnded method to look like the following:
if (diffLength > 4.0f)
{
float angle = atan2f(diff.y, diff.x);
_playerMissileSprite.zRotation = angle - SK_DEGREES_TO_RADIANS(90.0f);
_playerMissileSprite.position = _playerSprite.position;
_playerMissileSprite.hidden = NO;
float adjacent, opposite;
CGPoint destination;
// 1
angle = M_PI_2 - angle;
adjacent = _playerMissileSprite.position.y + Margin;
opposite = tanf(angle) * adjacent;
destination = CGPointMake(_playerMissileSprite.position.x - opposite, -Margin);
// 2
//set up the sequence of actions for the firing
SKAction *missileMoveAction = [SKAction moveTo:destination duration:2.0f];
SKAction *missileDoneMoveAction = [SKAction runBlock:(dispatch_block_t)^() {
_playerMissileSprite.hidden = YES;
}];
SKAction *moveMissileActionWithDone = [SKAction sequence:@[_missileShootSound, missileMoveAction, missileDoneMoveAction]];
[_playerMissileSprite runAction:moveMissileActionWithDone];
}
Add the following line to the end of the @implemenation MyScene section:
SKAction *_missileShootSound;
Also add this line at the bottom of the code inside initWithSize method:
_missileShootSound = [SKAction playSoundFileNamed:@"Shoot.wav" waitForCompletion:NO];
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 (each runs one after the other), starting with a sound action, followed by
moveTo. Once the sprite has reached its destination, themissileDoneMoveActionaction 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 = CGPointMake(_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 = CGPointMake(_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 = CGPointMake(_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 = CGPointMake(-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 MyScene.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 touchesEnded, change the code that creates the missileMoveAction action (the // 2 section) to the following:
float hypotenuse = sqrtf(adjacent*adjacent + opposite*opposite);
NSTimeInterval duration = hypotenuse / PlayerMissileSpeed;
//set up the sequence of actions for the firing
SKAction *missileMoveAction = [SKAction moveTo:destination duration:duration];
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 moveTo action. It’s a bit involved, but then it’s largely fire & forget because Sprite Kit does all the work of animating for you.








