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
Hitting Your Targets
Right now, the missile completely ignores the cannon – your spaceship might as well be firing a beam of green light!
That’s about to change. As before, you will use a simple radius-based method of collision detection.
Add a new constant to the source at the top of HelloWorldLayer.m:
const float CannonHitRadius = 25.0f;
For simplicity’s sake, you will assume that the missile itself doesn’t have a radius, so whenever its center point goes within the cannon hit radius, that will be sufficient to register as a collision. That’s precise enough for this game.
Add a new method:
- (void)updatePlayerMissile:(ccTime)dt
{
if (_playerMissileSprite.visible)
{
float deltaX = _playerMissileSprite.position.x - _turretSprite.position.x;
float deltaY = _playerMissileSprite.position.y - _turretSprite.position.y;
float distance = sqrtf(deltaX*deltaX + deltaY*deltaY);
if (distance < CannonHitRadius)
{
[[SimpleAudioEngine sharedEngine] playEffect:@"Hit.wav"];
_cannonHP = MAX(0, _cannonHP - 10);
_playerMissileSprite.visible = NO;
[_playerMissileSprite stopAllActions];
}
}
}
This should be old hat by now: you calculate the distance and then play a sound effect when the distance has become smaller than the hit radius.
Note that you need to call stopAllActions on the missile sprite, because you want it to stop moving. This tells the CCMoveTo action that it is no longer needed.
Call this new method from within update. Place it directly below the call to updatePlayer.
[self updatePlayerMissile:dt];
Build and run, then try it out. Finally you can inflict some damage on the enemy!
Challenges for the 1337
Here's a challenge for you: can you make the cannon shoot back at the spaceship?
Try to see if you can figure it out - you already know all the required pieces, and this will be some really good practice to make sure you understand what we've covered so far.
Try it out for yourself before you look at the solution!
[spoiler title="Make the cannon shoot back"]
To implement this on your own, all you have to do is create a new missile sprite (using CannonMissile.png), calculate the destination, and send the missile on its way. You know the angle because the turret already points at the player. The destination point for the CCMoveTo action is obviously the position of the player at that moment.
Collision detection with the player works the same way as before: the missile has hit as soon as the distance between the missile and the player becomes less than a certain radius. To make the game extra challenging for the player, allow the cannon to shoot more than one missile at a time.
[/spoiler]
Got that, and think you're some hot stuff? Here's another challenge for you!
Currently your missiles fly to their destination point in a straight line. But what if the missiles were heat-seeking? A heat-seeking missile adjusts its course when it detects that the player has moved.
You've got the power of trig on your side, so how would you do it? Hint: instead of calculating the speed and direction of the missile just once, you would do it again and again on each frame. Give it a try.
[spoiler title="Make the missile heat seeking"]
Since you're calculating the speed and direction of the missile on each frame, you can no longer use a CCMoveTo action. Instead, you have to do the animation by yourself. Continuously adjust the speed of the missile based on the new angle that it makes with the player. To read more about this sort of "seeking" behavior, check out the Game AI tutorial.
Make sure to give the guided missile a limited lifetime, so the player can avoid it if he keeps dodging it long enough, or the game might become a bit too hard to play!
[/spoiler]
How'd you do? Is your spaceship dodging guided missiles like Tom Cruise, or still flying around scot-free?
Adding an Orbiting Shield
To make the game more challenging, you will give the enemy a shield. The shield will be a magical asteroid sprite that orbits the cannon and destroys any missiles that come near it.
Add a couple more constants to the top of HelloWorldLayer.m:
const float OrbiterSpeed = 120.0f; // degrees per second
const float OrbiterRadius = 60.0f; // degrees
const float OrbiterCollisionRadius = 20.0f;
And some new instance variables as well:
@implementation HelloWorldLayer
{
...
CCSprite *_orbiterSprite;
float _orbiterAngle; // in degrees
}
I added the “in degrees” comments above because unlike the other angles, which were in radians, here you’ll work with degrees. They are just easier to wrap your head around.
Initialize the new sprite inside init after all the previous code:
_orbiterSprite = [CCSprite spriteWithFile:@"Asteroid.png"];
[self addChild:_orbiterSprite];
And add a new method:
- (void)updateOrbiter:(ccTime)dt
{
// 1
_orbiterAngle += OrbiterSpeed * dt;
_orbiterAngle = fmodf(_orbiterAngle, 360.0f);
// 2
float x = cosf(CC_DEGREES_TO_RADIANS(_orbiterAngle)) * OrbiterRadius;
float y = sinf(CC_DEGREES_TO_RADIANS(_orbiterAngle)) * OrbiterRadius;
// 3
_orbiterSprite.position = ccp(_cannonSprite.position.x + x, _cannonSprite.position.y + y);
}
The asteroid will orbit around the cannon. In other words, it describes a circular path, round and round and round and round. To accomplish this, you need two pieces: the radius that determines how far the asteroid is from the center of the cannon, and the angle that describes how far it has rotated around that center point.
This is what updateOrbiter does:
- It increments the angle by a certain speed (from the
OrbiterSpeedconstant), adjusted for the delta time. Because we as humans like to think of angles as anything between 0 and 360 degrees, you usefmodf()to wrap the angle around back to 0 once it becomes greater than 360. You cannot use the % operator for this, because it only works on integers, butfmodf()does the same thing for floats (andfmod()does the same thing for doubles). Wrapping the angles isn’t strictly necessary but it helps you stay sane when you’re trying to debug something like this. - It calculates the new x- and y-positions for the orbiter using the sine and cosine functions. These take the radius (which forms the hypotenuse of the triangle) and the current angle, and return the adjacent and opposite sides, respectively. More about this in a second.
- It sets the new position of the sprite by adding the x- and y-positions to the center position of the cannon.
You have briefly seen sinf() and cosf() in action, but it may not have been entirely clear how they worked. Sure, you have the formulas memorized (really? :]) and you know that both of these functions can be used to calculate the lengths of the other sides, once you have an angle and the hypotenuse.
But aren’t you curious why you can actually do that? I thought you were!
Let’s draw a circle:
The illustration above exactly depicts the situation of the asteroid orbiting around the cannon. The circle describes the path of the asteroid and the origin of the circle is the center of the cannon.
The angle starts at zero degrees but increases all the time until it ends up right back at the beginning. As you can see it, is the radius of the circle that determines how far away from the center the asteroid is placed.
So, given the angle and the radius, you can derive the x- and y-positions using the cosine and sine, respectively:
Now let’s take a look at a plot of a sine wave and a cosine wave:
On the horizontal axis are the degrees of a circle, from 0 to 360, or 0 to 2π radians if you’re a mathematician. The vertical axis usually goes from -1 to +1, but if your circle has a radius that is greater than one (and they tend to) then the vertical axis really goes from –radius to +radius.
As the angle increases from 0 to 360, find the angle on the horizontal axis in the plots for the cosine and sine waves. The vertical axis then tells you what the values for x and y are:
- If the angle is 0 degrees, then cos(0) is 1*radius but sin(0) is 0*radius. That corresponds exactly to the (x, y) coordinate in the circle: x is equal to the radius, but y is 0.
- If the angle is 45 degrees, then cos(45) is 0.707*radius and so is sin(45). This means x and y are both the same at this point on the circle. (Note: if you’re trying this out on a calculator, then switch it to DEG mode first. You’ll get radically different answers if it’s in RAD mode, no pun intended.)
- If the angle is 90 degrees, then cos(90) is 0*radius and sin(90) is 1*radius. You’re now at the top of the circle where the (x, y) coordinate is (0, radius).
- And so on… To get a more intuitive feel for how the coordinates in the circle relate to the values of the sine, cosine and even tangent functions, try out this cool interactive circle.
Make sense? Awesome. Did you also notice that the curves of the sine and cosine are very similar? In fact, the cosine wave is simply the sine wave shifted by 90 degrees. Go ahead and impress your friends and family with your knowledge of the mathematical origins of sine and cosine. :]
Back to coding. Add a call to updateOrbiter at the bottom of update:
- (void)update:(ccTime)dt
{
...
[self updateOrbiter:dt];
}
Build and run the app. You should now have an asteroid that perpetually circles the enemy cannon.
You can also make the asteroid spin around its own axis. Add the following line to the bottom of updateOrbiter:
_orbiterSprite.rotation = -_orbiterAngle;
By setting the rotation to negative _orbiterAngle, the asteroid always stays oriented in the same position relative to the cannon, much like the moon always shows the same side to the earth. Even though it looks like it isn’t spinning, it certainly is!
Remove the minus sign to give the asteroid extra spin that you can see. Pick whichever effect you like best. Build and run to play around with it for a bit.
Let’s give the orbiter a purpose. If the missile comes too close, the asteroid will destroy it before it gets a chance to do any damage to the cannon. Add the following at the bottom of updateOrbiter:
if (_playerMissileSprite.visible)
{
float deltaX = _playerMissileSprite.position.x - _orbiterSprite.position.x;
float deltaY = _playerMissileSprite.position.y - _orbiterSprite.position.y;
float distance = sqrtf(deltaX*deltaX + deltaY*deltaY);
if (distance < OrbiterCollisionRadius)
{
_playerMissileSprite.visible = NO;
[_playerMissileSprite stopAllActions];
_orbiterSprite.scale = 2.0f;
[_orbiterSprite runAction:[CCScaleTo actionWithDuration:0.5f scale:1.0f]];
}
}
No surprises for you here. It’s the same code you’ve seen several times now. Just remember to stop the CCMoveTo action that is on the missile sprite. For added visual effect, you also scale the asteroid sprite momentarily. This makes it look like the orbiter “ate” the missile.
Build and run to see your new orbiting shield in action.






