Domanda

I am trying to invoke a function that contains ccactioninterval in Cocos3d. I want to call that function at specific time intervals.When I tried NSTimer , i found that it works sometimes and sometimes not.

      NSTimer makeTarget=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(createTargets) userInfo:nil repeats:YES];

Here createTargets is the function that contains action events. when i run the function straightit works fine for single time. Problem comes when i try to schedule it. I ve tried different methods already explained for related questions . But nothing worked for me. . . .

Here is the code

-(void) addTargets {      
    NSTimer *makeTarget = [NSTimer scheduledTimerWithTimeInterval:2.0
              target:self selector:@selector(createTargets) userInfo:nil repeats:YES]; 
}

-(void)createTargets {
    CC3MeshNode *target = (CC3MeshNode*)[self getNodeNamed: @"obj1"];    
    int minVal=-5;
    int maxVal=5;    
    float avgVal; 
    avgVal = maxVal- minVal;      
    float Value = ((float)arc4random()/ARC4RANDOM_MAX)*avgVal+minVal ;          
    [target setLocation:cc3v(Value, 5.0, 0.0)];    
    CCActionInterval *moveTarget = [CC3MoveBy actionWithDuration:7.0 moveBy:cc3v(0.0, -10.0, 0.0)];     
    CCActionInterval *removeTarget = [CCCallFuncN actionWithTarget:self selector:@selector(removeTarget:)];       
    [target runAction:[CCSequence actionOne:moveTarget two:removeTarget]];   
}

-(void)removeTarget:(CC3MeshNode*)targ {  
    [self removeChild:targ];  
    targ=nil; 
}
È stato utile?

Soluzione

Without much code its hard to tell what you issues is, but here are some things to try apologies if any of this is obvious.


Are you holding onto a reference to the timer?

This might be useful for debugging. If you have a property called makeTargetTimer, then you could do this:

NSTimer * makeTargetTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(createTargets) userInfo:nil repeats:YES];
self.makeTargetTimer = makeTargetTimer // Save to a property for later use (or just use an iVar)

The only way to stop a re-occurring timer is to invalidate it. Therefore you could check to see if its been invalidated.

BOOL isInvalidated = [self.makeTargetTimer isValid];

Also you might want to do this in your dealloc method anyway:

- (void) dealloc {
    [_makeTargetTimer invalidate];  // Stops the timer from firing (Assumes ARC)
}

Are you scrolling when the even should be received?

If you want the timer to be fired while scrolling then you need to use NSRunLoopCommonModes. There is a excellent expiation in this question.

 [[NSRunLoop currentRunLoop] addTimer:makeTargetTimer forMode:NSRunLoopCommonModes]; 

What is your implementation of createTargets like?

  • Have you put NSLog statements on the body of this method. Are you certain its not being called?
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top