Dale Townsend
Dale Townsend

Reputation: 691

Continually run method while finger is held on the screen

I'm developing a game that has guns such as a revolver, rifle and shotgun. You choose a gun and shoot aliens that appear on the screen. I'm almost done, but I'm having a problem with shooting the aliens with automatic fire guns, such as a machine gun. For the single shot guns, I am using this to detect when an alien is in the crosshairs, and if it is, hiding it:

CGPoint pos1 = enemyufoR.center;
if ((pos1.x > 254) && (pos1.x < 344) && (pos1.y > 130) && (pos1.y < 165 && _ammoCount != 0))
{
    enemyufoR.hidden = YES;
    [dangerBar setProgress:dangerBar.progress-0.10];
    _killCount = _killCount+3;
    [killCountField setText: [NSString stringWithFormat:@"%d", _killCount]];

    timer = [NSTimer scheduledTimerWithTimeInterval: 4.0
                                             target: self
                                           selector: @selector(showrUfo)
                                           userInfo: nil
                                            repeats: NO];
}

This works fine for most guns, but for the machine gun I need it to continually check for the enemies position while the gun is firing. How would I do this?

Upvotes: 4

Views: 131

Answers (2)

Zhang
Zhang

Reputation: 11607

Um, when you tap your shoot button, you're obviously calling something like:

// --------------------------------------
// PSEUDO-CODE
// --------------------------------------
-(void)shootButtonPressed
{
    [self checkEnemies];
}

From that, why don't you just declare a BOOL variable and use that to check if finger is still pressed like this:

// --------------------------------------
// PSEUDO-CODE
// --------------------------------------

@interface MyGameClass
{
    // defaults to FALSE
    BOOL isTouching;
}

-(void)shootButtonPressed
{
    // assumes isTouching is a instance variable declared somewhere
    isTouching = YES;
    [self checkEnemies];
}

-(void)checkEnemies
{
    // check enemy action

    // ---------------------------------------------
    // when finger lifts off the screen, this 
    // isTouching variable will be reset to FALSE
    // so as long as isTouching is TRUE, we call
    // this same method checkEnemies again
    // ---------------------------------------------
    if(isTouching)
    {
        [self checkEnemies];
    }
}

// reset the isTouching variable when user finger is taken off the screen
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    isTouching = NO;   
}

Upvotes: 1

Pablo Alejandro Junge
Pablo Alejandro Junge

Reputation: 153

Check the timestam from an UITouch

Upvotes: 1

Related Questions