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.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

Contents

Hide contents

Trigonometry for Game Programming: Part 2/2

40 mins

Game Over, With Trig!

There is still more that you can do with sines and cosines. They’re not just useful for calculating things with triangles – they also come in handy for animations.

A good place to show an example of such an animation is the game over screen. Add a few new instance variables in the implementation block at the top of HelloWorldLayer.m:

@implementation HelloWorldLayer
{
    ...
    CCLabelTTF *_gameOverLabel;
    CCLayerColor *_darkenLayer;
    BOOL _gameOver;
    CFTimeInterval _gameOverElapsed;
}

And a new method:

- (void)checkGameOver:(ccTime)dt
{
    // 1
    if (_playerHP > 0 && _cannonHP > 0)  // not game over yet
    {
        return;
    }

    if (!_gameOver)
    {
        // 2
        _gameOver = YES;
        _gameOverElapsed = 0.0;
        self.accelerometerEnabled = NO;

        // 3
        _darkenLayer = [[CCLayerColor alloc] initWithColor:ccc4(0, 0, 0, 255)];
        _darkenLayer.opacity = 0;
       [self addChild:_darkenLayer];

        // 4
        NSString *text = (_playerHP == 0) ? @"GAME OVER" : @"Victory!";
        _gameOverLabel = [[CCLabelTTF alloc] initWithString:text fontName:@"Helvetica" fontSize:24.0f];
        _gameOverLabel.position = ccp(_winSize.width/2.0f + 0.5f, _winSize.height/2.0f + 50.0f);
        [self addChild:_gameOverLabel];
    }
    else
    {
        // 5
        if (_darkenLayer.opacity < 200)
        {
            float newOpacity = fminf(200.0f, _darkenLayer.opacity + 255.0f * dt);
            _darkenLayer.opacity = newOpacity;
        }
    }
}

This method both checks whether the game is done, and if so, handles the game over animation:

  1. The game keeps on going until either the player or the cannon runs out of hit points.
  2. When the game is over, set _gameOver to YES and disable the accelerometer.
  3. Create a new, all-black color layer and add it on top of everything else. Set its opacity to 0 so that it is completely see-through. Elsewhere in this method you will animate the opacity value of this layer so that it appears to fade in.
  4. Add a new text label and place it on the screen. The text is either “Victory!” if the player won or “Game Over” if the player lost.
  5. The above steps only happen once to set up the game over screen – every time after that, the code enters the else clause. Here you animate the opacity of the new color layer from 0 to 200 – almost completely opaque, but not quite.

Call checkGameOver at the bottom of update:

- (void)update:(ccTime)dt
{
    ...
    [self checkGameOver:dt];
}

And add a small snippet of logic to the top of ccTouchesEnded:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_gameOver)
    {
        CCScene *scene = [HelloWorldLayer scene];
        [[CCDirector sharedDirector] replaceScene:[CCTransitionZoomFlipX transitionWithDuration:0.5f scene:scene]];
        return;
    }
    ...
}

This restarts the game when the user taps on the game over screen.

Build and run, then try it out. Shoot at the cannon or collide your ship with it until one of you runs out of hit points. The screen will fade to black and the game over text will appear:

The game no longer responds to the accelerometer, but the animations still keep going. That gives it a nice twist!

This is all fine and dandy, but where are the sine and cosines? As you may have noticed, the fade in animation of the black layer was very linear. It just goes from transparent to opaque in a conventional fashion.

You can be better than conventional – you can use sinf() to subtly change the timing. This is often known as “easing” and the effect you will apply in particular is known as an “ease out”.

Add the new constant at the top of HelloWorldLayer.m:

const CFTimeInterval DarkenDuration = 2.0;

Next, change the code in the else statement in checkGameOver to:

- (void)checkGameOver:(ccTime)dt
{
    ...
    }
    else 
    {
        _gameOverElapsed += dt;
        if (_gameOverElapsed < DarkenDuration)
        {
            float t = _gameOverElapsed / DarkenDuration;
            t = sinf(t * M_PI_2);  // ease out
            _darkenLayer.opacity = 200.0f * t;
        }
    }
}

_gameOverElapsed keeps track of how much time has passed since the game ended. It takes two seconds to fade in the black layer (DarkenDuration). The variable t determines how much of that duration has passed by. It always has a value between 0.0 and 1.0, regardless of how long DarkenDuration really is.

Then you perform the magic trick:

t = sinf(t * M_PI_2);  // ease out

This converts t from a linear interpolation into one that breathes a bit more life into things:

Build and run to see the new “ease out” effect. If you find it hard to see the difference, then try it with that “magic” line commented out, or change the duration of the animation. The effect is subtle, but it's there.

Note: If you’re a big fan of Cocos2D actions, then you may have used the CCEaseSineIn action (or any of the other ease in variations) to accomplish a similar effect. Now you know how it works. :]

Note: If you’re a big fan of Cocos2D actions, then you may have used the CCEaseSineIn action (or any of the other ease in variations) to accomplish a similar effect. Now you know how it works. :]

There is one more thing I’d like to show you. Let’s make the game over text bounce, because things that bounce are always more fun.

Inside that else clause in checkGameOver, add the following so that the method looks like so:

- (void)checkGameOver:(ccTime)dt
{
    ...
    }
    else 
    {
        _gameOverElapsed += dt;
        if (_gameOverElapsed < DarkenDuration)
        {
            float t = _gameOverElapsed / DarkenDuration;
            t = sinf(t * M_PI_2);  // ease out
            _darkenLayer.opacity = 200.0f * t;
        }
        // Game Over Label Position
        float y = fabsf(cosf(_gameOverElapsed * 3.0f)) * 50.0f;
        _gameOverLabel.position = ccp(_gameOverLabel.position.x, _winSize.height/2.0f + y);
    }
}

OK, what's happening here? Recall what a cosine looks like:

If you take the absolute value of cosf() – using fabsf() – then the section that would previously go below zero is flipped. The curve already looks like something that bounces, don’t you think?

Because the output of these functions lies between 0.0 and 1.0, you multiply it by 50 to stretch it out a little. The argument to cosf() is normally an angle, but you’re giving it the _gameOverElapsed time to make the cosine move forward through its curve.

The factor 3.0 is just to make it go a bit faster. You can tinker with these values until you have something that you think looks cool.

Build and run to check out the bouncing text:

Screenshot 2013.04.20 16.32.03

You’ve used the shape of the cosine to describe the bouncing motion of the text label. These cosines are useful for all sorts of things!

One last thing you can do is let the bouncing motion lose height over time. You do this by adding a damping factor. Create a new instance variable in the HelloWorldLayer implementation block:

@implementation HelloWorldLayer
{
    ...
    float _gameOverDampen;
}

In checkGameOver, set _gameOverDampen. Do this at the beginning of the if block, like so:

- (void)checkGameOver:(ccTime)dt
{
    ...
    if (!_gameOver)
    {
        // 2
        _gameOver = YES;
        _gameOverDampen = 1.0f;
        ...
    }
    ...
}

In the else block, change the code underneath the "// Game Over Label Position" comment to be the following:

float y = fabsf(cosf(_gameOverElapsed * 3.0f)) * 50.0f * _gameOverDampen;
_gameOverDampen = fmaxf(0.0f, _gameOverDampen - 0.3f * dt);
_gameOverLabel.position = ccp(_gameOverLabel.position.x, _winSize.height/2.0f + y);

It’s mostly the same as before, but you multiply the y-value with the damping factor and, simultaneously, you reduce this damping factor slowly from 1.0 back to 0.0 (but never less than 0; that’s what the fmaxf() prevents). Build and run, then try it out!

Contributors

Over 300 content creators. Join our team.