user2529426
user2529426

Reputation: 31

Change an integer value after a time interval ios

I am making a game with powerups. I have 3 powerups. When a powerup is active, I use an integer to identify which one it is, 1, 2, or 3, with 0 representing no active powerups. Once I activate a powerup, I want it to expire after a time interval, say 10 seconds. How do I reset the identifier integer back to 0?

For example, one powerup speeds up the ship. Here is my update method.

-(void) update:(ccTime)dt
{
if (powerupIdentifier == 0)
{
    shipSpeed = 100;
}
if (powerupIdentifier == 1)
{
    shipSpeed = 200;
}


CCArray* touches = [KKInput sharedInput].touches;    
if ([touches count] == 1)
{
    //MAKES SHIP MOVE TO TAP LOCATION
    KKInput * input = [KKInput sharedInput];
    CGPoint tap = [input locationOfAnyTouchInPhase:KKTouchPhaseBegan];
    ship.position = ccp( ship.position.x, ship.position.y);
    if (tap.x != 0 && tap.y != 0)
    {
        [ship stopAllActions]; // Nullifies previous actions
        int addedx = tap.x - ship.position.x;
        int addedy = tap.y - ship.position.y;
        int squaredx = pow(addedx, 2);
        int squaredy = pow(addedy, 2);
        int addedSquares = squaredx + squaredy;
        int distance = pow(addedSquares, 0.5);
        [ship runAction: [CCMoveTo actionWithDuration:distance/shipSpeed position:tap]];//makes ship move at a constant speed

    }
}

}

Upvotes: 0

Views: 292

Answers (1)

nhgrif
nhgrif

Reputation: 62072

First, use an enum rather than an int.

typedef NS_ENUM(unsigned short, PowerUp) {
    PowerUp_Level0,
    PowerUp_Level1,
    PowerUp_Level2,
    PowerUp_Level3
};

Enum is far more readable, and is a lot more self-documenting then random integers.

Now, say we have a property:

@property (nonatomic, assign) PowerUp powerUp;

We can write a method to reset the power up:

- (void)resetPowerUp {
    self.powerUp = PowerUp_Level0;
}

Now, when we've set it to some non-zero value and need to reset it (after 10 seconds), it's as simple as this:

self.powerUp = PowerUp_Level2;
[self performSelector:@selector(resetPowerUp) withObject:nil afterDelay:10.0f];

Upvotes: 4

Related Questions