Search code examples
iosobjective-csprite-kit2d-games

Simple combo multiplier in sprite-kit


I am making a reaction game, where you can destroy enemys and earn points. Now I would like to have combo points if you destroy them fast and if there is a specific time gap the combo multiplier should go to zero again.

I would like to multiple the points like this: 2 * 2 = 4 * 2 = 8 * 2 = 16 * 2... (you get 2 points if you destroy an enemy).

I add the points here:

if (CGRectIntersectsRect(enemy.frame, player.frame)) {
        points = points + 1;
        [enemy removeFromParent];
    }

I could always multiply the current points with 2, but I want to reset the combo multiplier if there is specific amount of time without getting points.

I hope someone can help me. (code in objective c please)


Solution

  • It seems no more complicated than recording the time the last enemy was destroyed and then in the update: method deciding if the combo has elapsed as no more enemies were hit in whatever timeout period you allow.

    I am not familiar with Sprite kit, but the update appears to pass the current time; excellent. You will need to record the following:

    • timeout (time): The current timeout. This will reduce as the game progresses, making it harder.
    • lastEnemyKillTime (time): the time the last enemy was killed.
    • comboPoints (integer): How many points the user gets per hit. This will increase as the combo extends.
    • points (integer): The current score.

    So, something like this:

    @interface MyClass ()
    {
        NSTimeInterval _timeout;
        NSTimeInterval _lastEnemyKillTime;
        BOOL _comboFactor;
        NSUInteger _points;
    
    }
    @end
    

    I guess Sprite Kit uses an init: method; use it to initialize the variables:

    - (id)init
    {
        self = [super init];
        if (self != nil) {
            _timeout = 1.0;
            _lastEnemyKillTime = 0.0;
            _points = 0;
            _comboPoints = 1;
        }
    }
    

    The update: method would be something like:

    - (void)update:(NSTimeInterval)currentTime
    {
        BOOL withinTimeout = currentTime - _lastEnemyKillTime <= _timeout;
        if (CGRectIntersectsRect(enemy.frame, player.frame)) {
            _inCombo = withinTimeout;
            if (_inCombo)
                _comboPoints *= 2;
            _points += _comboPoint;
            _lastEnemyKillTime = currentTime;
            [enemy removeFromParent];
        } else if (_comboPoints > 1 && !withinTimeout) {
            _lastEnemyKillTime = 0.0;
            _comboPoints = 1;
        }
    }