Question

I am working on an OpenGL ES application where I have a spaceship with 6 guns. Each gun uses keyframe animation to interpolate between 2 sets of vertices of a start and end position.

I have a method rotateGun: that I pass the gunNumber variable to that refers to which gun should fire. When rotateGun: fires, it creates a laser blast that I move away from the ship through a vector pointing down the gun barrel at it's location when the method is called. This all works fine but I want to add random time intervals for each gun to fire since right now they appear to fire at the same time.

I've tried to create a time delay and fire off my rotateGun: method using performSelector:afterDelay:, but this doesn't work. I then attempted to use the method mainGunFire: after a delay and then call rotateGun: on the main thread… this also didn't work. By "didn't work" I mean that the NSLog I inserted just before my drawing calls within the rotateGun: method does print, but the guns and blasts are never drawn.

If I simply do a performSelectorOnMainThread to call rotateGun:, then the guns and blasts are drawn as before and the blasts appear to fire at the same time. I'm clearly not understanding something. Can someone please help me understand how to slightly randomize my laser blasts so they don't all fire at the same time? Thanks!

// Randomly Fire Gun
- (void)mainGunFire:(NSNumber *)gunNumber {

    // Perform the Gun animation and fire on main thread
    [self performSelectorOnMainThread:@selector(rotateGun:) withObject:gunNumber waitUntilDone:YES];

}

// Draw and Rotate the Guns
- (void)drawRotateGuns {

    // Only shoot if this is not a ship life
    if ( self.isLife == NO ) {

        // Gun 1

        // Set the pass variable to 1 and call the method
        // after a variable amount of time
        int randomTime = 0;
        //[self performSelector:@selector(mainGunFire:) withObject:[NSNumber numberWithInt:1] afterDelay:randomTime];
        [self performSelectorOnMainThread:@selector(rotateGun:) withObject:[NSNumber numberWithInt:1] waitUntilDone:YES];

        // Gun 2 ...

        // Gun 3 ...

    }
}
Was it helpful?

Solution

The easiest solution is to use !(rand()%some_number) instead of 1. Experiment with some_number value (it must be different for each gun). But it should be not very big.

For example if you use 2, then probability of !(rand()%2) == 1 is about 0.5. So if you're rendering 60 frames per second you'll get about 30 fires per second. For the !(rand()%20) you should get about 3 fires per second. Hope you get it. Some pseudocode:

if( !(rand()%2) ) {
     [gun1 fire];
}

if( !(rand()%3) ) {
     [gun2 fire];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top