I am using Cocos2d 2.1rc0.
I have this project that was working perfectly when I was not using CCSpriteBatchNode. Then I decided to use batch nodes to reduce draw calls and my problems started.
A lot of stuff is not working well. reorderChild is one. Another one is runAction and without runAction Cocos is useless.
This is an example of a method that works without batchNodes and do not work with it.
// move/rotate all objects
for (int i=0; i<[allObjects count]; i++) {
Card *object = [allObjects objectAtIndex:i];
[object stopAllActions];
CGPoint center = object.position;
center.x = center.x + 100;
center.y = center.y - 200;
CCMoveTo *moveAction = [CCMoveTo actionWithDuration:0.3f position:ccp(center.x, center.y)];
CCRotateTo *rotateAction = [CCRotateTo actionWithDuration:0.3 angle:0.0f];
CCSpawn *action = [CCSpawn actions:moveAction, rotateAction, nil];
[object runAction:[CCSequence actions: action,
[CCDelayTime actionWithDuration:0.1f],
nil]];
}
Exactly nothing happens.
I have tried to eliminate the CCSpanw and use runAction directly just with move and nothing works. If I use regular sprites, it works.
Objects in that array derive from a CCSprite based class.
Is there any workaround?
the solution is to cast the class to the object extracted from the array...
instead of
Card *object = [allObjects objectAtIndex:i];
this
Card *object = (Card *)[allObjects objectAtIndex:i];
After double-checking in a clean project that this isn't a weird side-effect of some kind, I have to say there's something fishy about your project. Hard to tell what, though.
What I did: create a sprite-batch, add a sprite to it, also store it in an array. In a scheduled method I'm receiving the sprite from the array (not casting) and run your action sequence posted above. It works fine, as expected.
The casting should not make any difference. Batched or non-batched sprite should not make any difference either.
If it does, something really weird is going on. After all the card object is the same with or without casting. If it were not actually running the runAction method, you'd be receiving an "unrecognized selector sent to instance" error. But that's not the case.
Try again without casting, after rebooting your device, your machine, cleaning the project in Xcode and rebuilding. Also test in debug and release configurations. I've had the weirdest issues that were gone after doing one of the above, and definitely all of the above. If that doesn't fix things, you can be sure it's a problem with the code (memory leak is my alltime favorite) or the project settings (ie uncommon compiler optimizations sometimes can have side-effects).
Step into the runAction method if it really doesn't run the action - I'm sure it will add the action to the action manager. Try with and without casting to see if there really is a different code path taken. I doubt it.
Related
I have already asked something similar but I can't figure out properly how to debug this. That's the question.
I added some Exceptions handler (catches all Objective-C) exceptions and that's the result of what I see:
The problem is with the setTexture method and it fails at the assertion verifying whether the texture name that needs to be displayed is the same as the one in the current sprite batch node.
This happens when trying to replace one scene with another but doesn't happen all the times. It has to do with the new scene as I tried to "isolate" the problem by calling the replace from a different part of the game and it still does give trouble.
In the game scene I have a couple of sprite sheets and sprite batch nodes but as I don't manage to isolate a sprite sheet id I cannot understand which sprite frame is giving me the problem, as well as I don't understand why this happens only sometimes.
I would like to:
understand which sprite frame name gives me the AssertionFailure
understand to which sprite sheet it belongs
This should help me to understand if it is a naming problem or if this has to do with something else.
Hoping not to be too lame with this question..
EDIT: I tried the answer but I am not able to read the 'fileName' information, here is what the debugger says "Summary unavailable":
That's how I create the filename property:
/** TMP: Bug solving filename */
#property (copy) NSString *fileName;
-(id) initWithTexture:(CCTexture2D*)texture rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize
{
if( (self=[super init]) )
{
self.fileName = [NSString stringWithFormat:#"GLUINT texture name: %i", texture.name];
self.texture = texture;
rectInPixels_ = rect;
rect_ = CC_RECT_PIXELS_TO_POINTS( rect );
offsetInPixels_ = offset;
offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ );
originalSizeInPixels_ = originalSize;
originalSize_ = CC_SIZE_PIXELS_TO_POINTS( originalSizeInPixels_ );
rotated_ = rotated;
}
return self;
}
-(id) initWithTextureFilename:(NSString *)filename rectInPixels:(CGRect)rect rotated:(BOOL)rotated offset:(CGPoint)offset originalSize:(CGSize)originalSize
{
if( (self=[super init]) )
{
self.fileName = fileName; //TMP
texture_ = nil;
textureFilename_ = [filename copy];
rectInPixels_ = rect;
rect_ = CC_RECT_PIXELS_TO_POINTS( rect );
offsetInPixels_ = offset;
offset_ = CC_POINT_PIXELS_TO_POINTS( offsetInPixels_ );
originalSizeInPixels_ = originalSize;
originalSize_ = CC_SIZE_PIXELS_TO_POINTS( originalSizeInPixels_ );
rotated_ = rotated;
}
return self;
}
In such cases logging is your friend. Every time you create a CCAnimate action (or CCAnimation) you should log something like this:
// during 'create sprite frames from sprite frame names' loop
NSLog(#"adding sprite frame name for CCAnimate: %#", spriteFrameName);
// after CCAnimate was created
NSLog(#"creating CCAnimate %# with sprite frames: %#, animate, arrayOfSpriteFrames);
You will probably want to add more detail, like which sprite frame names were added to that CCAnimate. You may also have to add additional logging if you cache CCAnimations and reuse them later (log each CCAnimation when reused).
Now when you receive that error you should select the [CCSprite setDisplayFrame:] method in the call stack. The debugger will then show you the value for the CCSpriteFrame it wants to set. Look for the pointer value, it will read something like 0x254fb22e.
Search for that value in your log, this will bring you back to one of the "creating CCAnimate.." logs. From the log lines above you can see the sprite frame names it contains. Since you also logged the 'arrayOfSpriteFrames' you can get their pointer value, compare it with the pointer value of the CCSpriteFrame that caused the assertion.
When you have a match, and it's the fourth item in the sprite frame array, just look up the name of the fourth sprite frame name added to the CCAnimate.
There may be a quicker way to do this depending on which information is available in the debugger (and how well versed you are in debugging), but this is one approach that will definitely lead you to the offending sprite frame name in relatively short time.
Note that the pointer values are not unique - it's possible that a different CCAnimate was created with the same pointer value. Especially if there's a high frequence of CCAnimate playing and stopping it can happen that another CCAnimate is allocated at the exact same memory location of a previous one. So be wary if the results don't seem to match up. A quick way to find out is to test on different devices or Simulator vs. Device, as pointer values and allocation strategies vary.
You don't need to log which sprite frame name belongs to which texture atlas. Simply open the plist of each atlas and search for the sprite frame name. The plist is an XML file.
Tip: common cause for this problem can be having the same sprite frame name in two different texture atlases - cocos2d may use either texture when you request a sprite frame with a duplicate name.
Another Tip: if the logging seems daunting, I'd simply do the following:
open source code for CCSpriteFrame class
add a NSString* property 'filename' with 'copy' attribute
every time you create a CCSpriteFrame object, assign the filename to the CCSpriteFrame
Now whenever you see a CCSpriteFrame in the debugger, it'll show you the associated filename in the debugger view.
ok , looks like you have been there before ... Comment the first NSAssert, uncomment the if block. Then put a break point on the newly uncommented NSAssert. Execution will pause BEFORE the exception, and you should be to inspect the iVars of each class instance in the call stack (at least i can with AppCode, hope xCode allows that). Maybe you will get enough of a hint to figure out which texture/animation/batchnode is giving you a hard time.
Also ... fyi. Whenever i start a project with cocos2d (any version) , i apply some 'standard' fixes to it so that my life will be easier for debugging. A standard 'patch' is to add a name to CCNode, which i set to some meaningful value : always. Also i override the descpription method to return MY name. Assigning meaningful names has helped me many times, especially when walking down (or up) the node hierarchy to figure out a bug. I also nuke many of the NSAsserts and whenever possible (especially in ctors), return nil and log an error message. As per Stefen's suggestion, if a cocos2d ctor returns me a nil, i spew out an error log message. I can then break on that log statement and drill-down the issue.
I've recently added the CCLayerPanZoom cocos2d extension to my project and got my game scene zooming and scrolling just like I want. Now when the player takes certain actions, I want to be able to disable the pan/zoom temporarily while they perform an action but can't figure out how to do it. I searched around and found the following code in a forum but it doesn't work or I don't know how to use it.
Does anyone know how to do this properly either with different code or the code below?
-(void)enableTouches:(BOOL)enable {
if(enable) {
[[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:0];
_panZoomLayer.isTouchEnabled = YES;
CCLOG(#"LayerPanZoom enabled.");
} else {
[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
_panZoomLayer.isTouchEnabled = NO;
CCLOG(#"LayerPanZoom disabled.");
}
}
I finally figured it out and figured I would post the answer back up here to share. The code I posted wasn't working because I was sending back self instead of the _panZoomLayer. So here are the steps to get this working yourself.
Implement the CCLayerPanZoom into your project as described by the documentation.
Add the following code as a method to call on your new CCLayerPanZoom class.
-(void)enableTouches:(BOOL)enable {
if(enable) {
[[CCTouchDispatcher sharedDispatcher] addStandardDelegate:_panZoomLayer priority:0];
CCLOG(#"LayerPanZoom enabled.");
} else {
[[CCTouchDispatcher sharedDispatcher] removeDelegate:_panZoomLayer];
CCLOG(#"LayerPanZoom disabled.");
}}
NOTE: Make sure to put the instance of the parent class as the delegate to remove.
In order to re-enable and have it function properly, you have to remove all the entries from the array in the CCLayerPanZoom class before calling to re-register the delegate. I created a new method in the CCLayerPanZoom class as follows and just call it right before the addStandardDelegate method above.
-(void)removeTouchesFromArray {
[self.touches removeAllObjects];
}
Then it all works great! Took me a while to learn how to use this extension but it works perfect once you figure it all out. I can single finger pan, double finger zoom/pan, set center location for entire scene, limit panning past edges, and set min/max scales. I know people have had a lot of issues with this but it is a great extension, just takes some messing around with to understand it. Let me know if you have any questions. Hope this helps someone else.
I have a CCRepeatForever action with a tag of 20. I call this:
[player stopActionByTag:20];
Noting happens.
I call this:
[player stopAllActions];
It stops. Any idea? The action is created like this and runs fine:
CCRepeatForever *repeat=[CCRepeatForever actionWithAction:animate];
repeat.tag=20;
[player runAction:repeat];
update: i also tried setting animate.tag=21 and stopping that action by itself or in addition to the repeat action, but neither works.
This should work, I made a quick test with stopActionWithTag using CCRepeatForever and it stops it correctly.
I can only imagine two cases where it wouldn't work:
You have more than one action with the tag = 20 running on the same object.
The object you send runAction to is a different object than the one you send stopActionByTag to.
The former is easy to check. If this code fixes your problem, you're running multiple actions with the same tag on the player object:
while ([player getActionByTag:20]) {
[player stopActionByTag:20];
};
The latter is rather unlikely but possible. One way to find out is to set a breakpoint on the runAction line and note the address of the player variable. Then set another breakpoint at the stopActionByTag line and compare that player's address with the previous one. If they're not the same, then that would be the problem.
I'm getting stuck to implement some Cocos2D animations for my Tetris clone(that works perfectly, no logic bugs, i just want to perform some smooth animation when deleting rows).
The current code(no animation) just drops the block position, like this:
block.position = ccp(block.position.x, block.position.y - kBlockSize);
This happens in a for loop for, classic tetris programming. But when i try to animate, like this:
id move = [CCMoveBy actionWithDuration:0.5f position:(0, -kBlockSize)];
[block runAction:move];
Some blocks just moves down once, even tough the action may be called multiple times for the same block(when breaking more than one row for example)...
Why that happens ? I know it's a little bit confusing, but the point is that i'm doing the same stuff and getting different results...i could post more code to help clarify!
Thanks!
I'm quite sure actions are parallel operations so you could be calling a CCMoveBy action before a previous one is completed. Some alternatives I have used are...
Monitor for when the action completes by using a CCSequence finishing with a CCCallFunc action that sets a flag. Something like...
id myAction = [[CCSequence runWithActions:[CCMoveBy actionWithDuration:0.5f position:(0, -kBlockSize)], [CCCallFunc actionWithTarget:self selector:#selector(myFunc)], nil]
Roll your own solution using a velocity variable in a tick or update function where you can get a hold of delta time/# of ticks since the last update
Hope some of that helps.
Thank you guys, those answers help me a lot!
I've tried CCSequences before posting here, but without success.
The problem was the following:
Inside the CCSequence that deletes a row, i have 2 actions: the first one fades out the entire row of blocks(duration of x seconds), and the second one drops all the blocks above the row(duration of y seconds).
This works fine if ONLY ONE row needs to be deleted, because if there is more than one row, the next CCSequence starts nearly the same time the previous, reading a incorrect position of the blocks above, leading to a incorrect cascade of blocks.
I solved that using a longer CCSequence, that takes a CCCallFuncND as the last argument:
id fadeOutSequence = [CCSequence actions:fadeout, destroyBlocks, notifyFadeFinish, nil];
//inside method specified for notifyFadeFinish:
id dropAbove = [CCSequence actions: dropBlocks, notifyDropFinish, nil];
//inside method specified for notifyDropFinish
//start a new delete sequence, if there is more rows to delete.
Now going to implement gravity mode, thanks again!
I'm using Cocos2d to write game for iPhone.
Here's the problem.
I have CCSprite and CCAction which is run on it.
CCSprite texture;
CCAction anim_action;
"Anim_action" is a CCRepeatForever action.
Now I want to check if this animation is running.
First I though I can use [isDone] function, but I think it doesn't work on CCRepatForever actions (I'm not sure - this opion is based on my tests)
So how to check if this animation is already running on my "texture"?
Maybe there is a way to get name of action which is running on texture at the moment?
It may be also useful!
There is a way to check if a specific action runs on your texture. Use:
CCAction *action = [texture getActionByTag:kAsignedActionTag];
where kAsignedActionTag is the tag assigned to the your animation.
anim_action.tag = kAsignedActionTag;
If your action is still running the getActionByTag method will not return nil.
I don't believe there's a way to directly tell if a CCRepeatForever action has completed since the isDone would make no sense, but there are some techniques you can use to essentially provide a callback to indicate if something is still running:
Override the step: method and call out to something that checks the interval - when it exceeds a threshold you can assume completion...kinda'
Wrap the inner action of the CCRepeatForever with a CCSequence. The first action of the sequence would be your repeated action and the second would be a CCCalFunc, again indicating that the action is still running
Subclass the CCRepeatForever and override the dealloc so you can fire a callback when the action is killed and released
You can easily use [isDone] while appling an effect
- (void)shakeThatThingOn: (BOOL)on { //you can return BOOL and get if the animation is working or not
if (on == YES){
id shaky2 = [CCShaky3D actionWithRange:3 shakeZ:NO grid:ccg(15,10) duration:5];
if (![shaky2 isDone])
[self runAction:[CCSequence actions:shaky2,[CCStopGrid action],nil]];
}
else {//this else is being called when you turn off animation (it's just 0.2s continuation after turning off - for better visual effect.
[self stopAllActions];
id shaky2 = [CCShaky3D actionWithRange:3 shakeZ:NO grid:ccg(15,10) duration:0.2];
[self runAction:[CCSequence actions:shaky2,[CCStopGrid action],nil]];
}}
and control it by simple BOOL if it's on or off.
I don't know if it's what you mean, but hope it'll help anyway.
If you know how many actions will be running on the sprite, or if the animation is the only action, then you can infer that the animation is running by checking the sprite's total number of running actions.
if ([texture numberOfRunningActions] > 0) //animation is running
or
if ([texture numberOfRunningActions] > someNumber) //if you had other actions running