Check if an action is currently running? - objective-c

Is it possible to check if there are actions currently running in a CCNode class in Cocos2d? I'd like to know if a CCMoveBy is still running or not.

You can use [self numberOfRunningActions] on any CCNode. In your case, it sounds like you want to know if there are simply any actions running or not, so it's not a big deal to know the exact number beforehand.

We can easily check if specific actions run by using getActionByTag method and action.tag property.
There is no need to introduce the CCCallFuncN callbacks or counting numberOfRunningActions.
Example.
In our app it is important to let the jumpAction to be finished prior to executing another jump. To prevent triggering another jump during an already running jump action
the critical jump section of code is protected as follows:
#define JUMP_ACTION_TAG 1001
-(void)jump {
// check if the action with tag JUMP_ACTION_TAG is running:
CCAction *action = [sprite getActionByTag:JUMP_ACTION_TAG];
if(!action) // if action is not running execute the section below:
{
// create jumpAction:
CCJumpBy *jumpAction = [CCJumpBy actionWithDuration:jumpDuration position:ccp(0,0) height:jumpHeight jumps:1];
// assign tag JUMP_ACTION_TAG to the jumpAction:
jumpAction.tag = JUMP_ACTION_TAG;
[sprite runAction:jumpAction]; // run the action
}
}

You can always add a method to indicate when the method is finished, and then toggle some BOOL or something like that to indicate it is not running, and put a start method to toggle the BOOL to indicate it started:
id actionMove = [CCMoveTo actionWithDuration:actualDuration
position:ccp(-target.contentSize.width/2, actualY)];
id actionMoveDone = [CCCallFuncN actionWithTarget:self
selector:#selector(spriteMoveFinished:)];
id actionMoveStarted = [CCCallFuncN actionWithTarget:self
selector:#selector(spriteMoveStarted:)];
[target runAction:[CCSequence actions:actionMoveStarted, actionMove, actionMoveDone, nil]];
Modified from here.
In the two #selector methods:
-(void) spriteMoveStarted:(id)sender {
ccMoveByIsRunning = YES;
}
and:
-(void) spriteMoveFinished:(id)sender {
ccMoveByIsRunning = NO;
}
where ccmoveByIsRunning is the BOOL I'm referring to.
EDIT: As xus has pointed out, you should actually not do this and instead use [self numberOfRunningActions] as others have pointed out.

Related

CCActionDelay not working as expected

What I have is a method that creates CCSprites:
-(void)createDebrisAtPosition:(CGPoint)position{
NSInteger numberOfPieces = [random randomWithMin:5 max:20];
for (int i=0; i<numberOfPieces; i++) {
CCSprite *debris = [CCSprite spriteWithImageNamed:#"debri.png"];
debris.position = position;
debris.physicsBody = [CCPhysicsBody bodyWithRect:CGRectMake(0, 0, debris.contentSize.width, debris.contentSize.height) cornerRadius:0];
debris.physicsBody.collisionType = #"debris";
debris.name = #"Debris";
CCActionRemove *removeAction = [CCActionRemove action];
CCActionSequence *sequence = [CCActionSequence actions:[CCActionDelay actionWithDuration:2.0], removeAction, nil];
[physics addChild:debris];
//physics is a CCPhysicsNode here
[debris runAction:sequence];
}
}
This method then gets invoked during specific collision events:
-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair enemy:(EnemyNode*)enemy projectile:(ProjectileNode*)projectile
{
[enemy removeFromParent];
[projectile removeFromParent];
[self createDebrisAtPosition:enemy.position];
return NO;
}
Expected behavior: CCSprites should appear and then get removed only after 2.0 secs.
Actual behavior: CCSprites appear for a split-second, then instantly get removed.
I also tried CCActionInterval, CCActionEaseOut, but they didn't work (And they shouldn't, according to the docs, but CCActionDelay — should, but not working). I changed the order of method invocation (runAction after and before addChild), as well as the order of action invocation this didn't work as well. Don't mind the CCActionDelay declaration directly in the CCActionSequence — I tried to declare it as a separate variable, with zero luck.
What am I misunderstanding here?
I'm new here so I'm not allowed to comment yet (this would perhaps be better suited as a comment) but: I haven't been able to recreate your problem. The problem is not related to CCActionDelay or the actions you are running on the debris sprite. You can test this yourself by running your sequence in a different setup. Ergo: there must be a problem somewhere else in your code. I'm sorry, but I cannot help any further based on the example code you've posted.

How to run two methods in sequence at time delay?

[self goToStage:currentStage];
[actor deathAnimation];
I have these two methods. I want to call it one by one in sequence. When one is completed after second one is started.
//this method used in nsobject subclass
-(void)deathAnimation {
//Play death animation
}
//this method in cclayer subclass
-(void)goToStage:(int)stage {
//changing scene
}
IN my tick function at particular event i want to call in seqeuence
I use following code but it not working
[CCSequence actions:[CCCallFunc actionWithTarget:actor selector:#selector(deathAnimation)], [CCDelayTime actionWithDuration:4.0], [CCCallFuncN actionWithTarget:self selector:#selector(goToStage:)], nil];
Now what i do? Please tell me.. Is there something wrong?
You can use CCDelayTime, that is used to give a delay, and CCCallBlock,to pass a method to be invoked, like this:
[self runAction:[CCSequence actions:[CCDelayTime actionWithDuration:1],
[CCCallBlock actionWithBlock:^{[self goToStage:currentStage];}],
[CCDelayTime actionWithDuration:1],
[CCCallBlock actionWithBlock:^{[actor deathAnimation}], nil]];
Define a block in you inteface as e.g.
typedef void(^MyCompletion)(void);
edit you deathAnimation to take a block parameter as
- (void)deathAnimationWithCompletion:(MyCompletion)finish {
//..death animation
//...
//when animation finishes
finish(); // This will call your completion block
}
Call this method as
[self deathAnimationWithCompletion:^{
[self goToStage:2];
}];
You can read up on blocks at Ray Wenderlichs fantastic blog.
Hope it helps!
EDIT DUE TO COMMENT
In cocos2d I think you can also make a sequence like this
id aFuncCall = [CCCallFunc actionWithTarget:self selector:#selector(deathAnimation)];
id antoherFuncCall = [CCCallFunc actionWithTarget:self selector:#selector(goToSecondStange:)];
CCSequence *sequence = [CCSequence actions:aFuncCall,anotherFuncCall, nil];
[self runAction:sequence];
But my cocos2d programming skills are bit outdated so not sure if this works...
You can call
[actor deathAnimation];
at the end of the goToStage function, that way it will execute everything in goToStage before calling deathAnimation.
You could put a delay timer in the goToStage if you require it to wait for a specific amount of time.

This animation is not functioning in this method

I'm having a lot of trouble figuring this one out. This method is imported from another class into my viewController.m It works fine if I copy the code into an IBAction in the same file. And the "test midi" is logging when it is supposed to. So the IBOutlets and animation code seem OK but for some reason this method does not do what it is supposed to
- (void) source:(theSource*)data dataReceived:(const dataList *)theList
{
led.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"led-highlighted.png"],[UIImage imageNamed:#"led-passive.png"],nil];
led.animationDuration = 0.3;
led.animationRepeatCount = 20;
[led startAnimating];
NSLog(#"test");}
it also doesn't work if I simply put this to swap the image. The method is being called because it is logging to console.
midiLed.image = [UIImage imageNamed:# "led-highlighted.png"];
The problem may lie in how you are calling this method. It should be on the main thread, and after calling it, your code should return to the run loop (i.e. your code should be "done") before changes to the user interface will have effect.
If this doesn't help you find it, please share the code calling this method.
What thread is -source:dataReceived: being called on? If you're using CoreMIDI, your MIDI-received function will get called on a separate, high-priority thread.
You should not touch the UI from a non-main thread, because UIKit isn't thread safe.
Here's one way to get the UI running on the main thread:
- (void) source:(theSource*)data dataReceived:(const dataList *)theList
{
dispatch_async(dispatch_get_main_queue(), ^{
led.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"led-highlighted.png"],[UIImage imageNamed:#"led-passive.png"],nil];
led.animationDuration = 0.3;
led.animationRepeatCount = 20;
[led startAnimating];
NSLog(#"test");
});
}

Confounding Cocoa problem — program hangs unless there’s an unrecognised method call

Bear with me, this one is hard to explain. I hope some hero out there knows what’s going on here. Some history needed;
One of my cocoa objects, “Ball” represents a small graphic. It only makes sense within a view. In some of the Ball’s methods, it asks the view to redraw. Most importantly, it asks the view to redraw whenever the Ball’s position parameter is set. This is achieved in the setter.
Here’s the mouthful, as suggested:
In View.m
- (void)mouseUp:(NSEvent *)theEvent {
if (![runnerPath isEmpty]) {
[walkPath removeAllPoints];
[walkPath appendBezierPath:runnerPath];
[runnerPath removeAllPoints];
[[self held] setStep:0];
[[self held] setPath:walkPath];
[NSTimer scheduledTimerWithTimeInterval:.01 target:[self held] selector:#selector(pace) userInfo:nil repeats:YES];
}
}
In Ball.m
- (void)pace {
CGFloat juice = 10;
BOOL loop = YES;
while (loop) {
if ([self step] == [[self path] elementCount]) {
if ([[self timer] isValid]) {
[[self timer] invalidate];
}
[[self path] removeAllPoints];
// #throw([NSException exceptionWithName:#"test" reason:#"reason" userInfo:nil]);
}
if (loop) {
CGFloat distance;
NSPoint stepPoint;
if ([[self path] elementCount] > 0) {
NSPoint returnPoints[2];
[[self path] elementAtIndex:[self step] associatedPoints:returnPoints];
stepPoint = returnPoints[0];
distance = pixelDistance([self position], stepPoint);
}
if (distance <= juice) {
[self setPosition:stepPoint];
if (distance < juice) {
juice -= distance;
loop = YES;
[self setStep:[self step]+1];
} else {
loop = NO;
}
} else {
NSPoint cutPoint = moveAlongBetween([self position], stepPoint, juice);
[self setPosition:cutPoint];
loop = NO;
}
}
}
}
could you also tell how you handle exceptions? since normally an unrecognized selector will end your program. Maybe you need an exception rather than an unrecognized selector. Try:
#throw([NSException exceptionWithName:#"test" reason:#"reason" userInfo:nil]);
If this would fix it as well, you're doing something after this code which freezes the app.
edit: thanks for the code update.
There's some weird stuff going on here! I'm not going to rewrite the whole thing, so here's some pointers:
first of all: you're looping inside some routine that is called from a timer loop. Is that intended? There is no way to pause execution within that while() loop, so it will happen in a blink anyway. You would need to keep some state information in the class. E.g. adding a loop counter every time pace is called.
second: if you start a timer, it will call your selector with the timer as an argument. So define the function as -(void)pace:(NSTimer*)timer, and use timer, not [self timer] (the latter will not be your timer anyway, if you don't assign it!)
third: you're firing 100 times a second. That is a lot, and presumably higher than the refresh rate of any device you're writing this for. I think 20/sec is enough.
fourth: to be sure, if you change it to -(void)pace:(NSTimer*)timer, don't forget to use #selector(pace:) (i.e. don't forget the :)
fix those things, and if it's still broken, update your question again and put in comment so we will know. Good luck!
Try calling
for (NSView *each in [self views]) {
...
}
I'm assuming that views is an array, so fast enumeration applies to it directly and there is no need to call allObjects.
A couple of other points.
Have you set a Global breakpoint of objc_exception_throw? This will apply to all Xcode projects and is so useful I'm surprised it isn't set by default.
You say you looked at the Console for errors. I take it, then, that you didn't set a breakpoint on the code and step into it to see exactly what is happening when your execution reaches that point? Have a look at the Xcode Debugging Guide

How do I update a progress bar in Cocoa during a long running loop?

I've got a while loop, that runs for many seconds and that's why I want to update a progress bar (NSProgressIndicator) during that process, but it updates only once after the loop has finished. The same happens if I want to update a label text, by the way.
I believe, my loop prevents other things of that application to happen. There must be another technique. Does this have to do with threads or something? Am I on the right track? Can someone please give me a simple example, how to “optimize” my application?
My application is a Cocoa Application (Xcode 3.2.1) with these two methods in my Example_AppDelegate.m:
// This method runs when a start button is clicked.
- (IBAction)startIt:(id)sender {
[progressbar setDoubleValue:0.0];
[progressbar startAnimation:sender];
running = YES; // this is a instance variable
int i = 0;
while (running) {
if (i++ >= processAmount) { // processAmount is something like 1000000
running = NO;
continue;
}
// Update progress bar
double progr = (double)i / (double)processAmount;
NSLog(#"progr: %f", progr); // Logs values between 0.0 and 1.0
[progressbar setDoubleValue:progr];
[progressbar needsDisplay]; // Do I need this?
// Do some more hard work here...
}
}
// This method runs when a stop button is clicked, but as long
// as -startIt is busy, a click on the stop button does nothing.
- (IBAction)stopIt:(id)sender {
NSLog(#"Stop it!");
running = NO;
[progressbar stopAnimation:sender];
}
I'm really new to Objective-C, Cocoa and applications with a UI. Thank you very much for any helpful answer.
If you are building for Snow Leopard, the easiest solution is in my opinion to use blocks and Grand Central Dispatch.
The following code shows you how your startIt: method would look like when using GCD.
Your stopIt: method should work fine as you wrote it. The reason why it wasn't working before is that mouse events happen on the main thread and thus the button didn't respond to you because you were doing work on the main thread. This issue should have been resolved now as the work has been put on a different thread now with GCD. Try the code, and if it doesn't work, let me know and I will see if I made some errors in it.
// This method runs when a start button is clicked.
- (IBAction)startIt:(id)sender {
//Create the block that we wish to run on a different thread.
void (^progressBlock)(void);
progressBlock = ^{
[progressbar setDoubleValue:0.0];
[progressbar startAnimation:sender];
running = YES; // this is a instance variable
int i = 0;
while (running) {
if (i++ >= processAmount) { // processAmount is something like 1000000
running = NO;
continue;
}
// Update progress bar
double progr = (double)i / (double)processAmount;
NSLog(#"progr: %f", progr); // Logs values between 0.0 and 1.0
//NOTE: It is important to let all UI updates occur on the main thread,
//so we put the following UI updates on the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
[progressbar setDoubleValue:progr];
[progressbar setNeedsDisplay:YES];
});
// Do some more hard work here...
}
}; //end of progressBlock
//Finally, run the block on a different thread.
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue,progressBlock);
}
You can try this code ..
[progressbar setUsesThreadedAnimation:YES];
I believe, my loop prevents other things of that application to happen.
Correct. You need to break this up somehow.
One way would be a timer, with you whittling away the queue a little at a time in the timer callback. Another would be to wrap the code to handle one item in an NSOperation subclass, and create instances of that class (operations) and put them into an NSOperationQueue.
Does this have to do with threads or something?
Not necessarily. NSOperations run on threads, but the NSOperationQueue will handle spawning the thread for you. A timer is a single-threaded solution: Every timer runs on the thread you schedule it on. That can be an advantage or a disadvantage—you decide.
See the threads section of my intro to Cocoa for more details.
This worked for me, which is a combination of answers from others that did not seem to work (for me at least) on their own:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
//do something
dispatch_async(dispatch_get_main_queue(), ^{
progressBar.progress = (double)x / (double)[stockList count];
});
//do something else
});