Sprite animation issues.
Using this example which seems to work for others:
How to create animation in cocos2d 3.0?
So I do this:
NSMutableArray *ballAnimFrames = [NSMutableArray array];
for(int i = 1; i <= 11; ++i)
{
[ballAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache]
spriteFrameByName: [NSString stringWithFormat:#"discoball1200x2008c16-%d.png", i]]];
}
CCAnimation *ballAnim = [CCAnimation
animationWithSpriteFrames:ballAnimFrames delay:0.1f];
discoBallSprite = [CCSprite spriteWithImageNamed:#"discoball1200x2008c16-1.png"];
discoBallSprite.position = ccp(upper1Body.position.x,upper1Body.position.y-200);
CCActionAnimate *animationAction = [CCActionAnimate actionWithAnimation:ballAnim];
CCActionRepeatForever *repeatingAnimation = [CCActionRepeatForever actionWithAction:animationAction];
discoBallSprite.scaleX = 0.25;
discoBallSprite.scaleY = 0.25;
[discoBallSprite runAction:repeatingAnimation];
[self addChild:discoBallSprite z:10];
I get the following error:
'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
Obviously the error message is saying my image file is nil but it seems perfectly fine.
I tried renaming files to remove the extra "-" character but no change (I also renamed files outside of Xcode and re-imported with new name).
All my images are in Resources folder.
I tried moving images out of Resources folder to next level up but still the error.
The naming of them seems fine.
Any ideas what else to check?
Make a sprite sheet, add it to your int
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"YourAnim.plist"];
Now in the animation code
[ballAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [YourAnim.png", i]]];
When you make a sprite sheet it makes two things, 1) a png with the sprites and 2) a plist with the coordinates
if you so decide to use the program I told you about make sure you set it to cocos2d
See The code Link
Now Change for Cocos2dV3 is below.
In the link code there is CCAnimation that is replace by CCActionAnimate in V3 and also CCRepeatForever is replace by CCActionRepeatForever in V3.
Also check your .plist images may be 10 althougt in for condition it get 11th image in it. so may be that is your problem to insert image in array,
replace and try.
for(int i = 1; i < 11; ++i)
{
// Code
}
Change it work fine.
Related
probably this is a simple problem to solve, since I'm quite new.
I have a scene with a waiter holding a tray of food
(the food is a random CCSprite choosen from an array)
each time he comes onscreen he holds a new piece of food
(the user touches the food and the waiter walks off to return
again with a new piece of food
however I cant seem to delete the old peice of food from the screen
as it says the child is already added...
any help would be great
-(id) init
{
///other code then...
waiterOnSCreen
= [CCSprite spriteWithSpriteFrameName:#"CatUP.png"];
waiterOnSCreen.position = ccp(CatOffSCreenPosX, catXpos);
[self addChild:waiterOnSCreen z:0];
//moving the waiter
// the random food sprite is added later to the waiter
// [waiterOnSCreen addChild:myRandomSprite];
}
-(void)LoadRandomFood
{
///I make my array here then and add CCSprites
RandomFood = [[NSMutableArray alloc]initWithObjects:
//cake,
RandomMuffin,
RandomMeat,
RandomCake,//
nil];//
int i = 0;
int count= [RandomFood count];
if (i < count)
{
int i = arc4random() % [RandomFood count];
myRandomSprite = (CCSprite *)[RandomFood objectAtIndex:i];
//waiterOnSCreen is a CCSprite added on the init
[waiterOnSCreen addChild:myRandomSprite];
myRandomSprite.position=ccp(290,220);
myRandomSprite.tag = RandomFoodTag;
}
}
later
in if(CGRectContainsPoint(waiterOnSCreen.boundingBox, location))
{
//trying to remove the food here
//Ive already tried to remove the sprite using
[self removeChildByTag:RandomeObjectTag];
//and also
CCSprite *wantedSprite = (CCSprite *)[self getChildByTag:RandomFoodTag];
[wantedSprite removeFromParentAndCleanup:YES];
}
}
Im guessing its also crashing 'child already added. It can't be added again'
as its trying to add RandomMuffin,RandomMeat,RandomCake, again
im not too sure how to fix that.
You shouldn't need to create another array just to delete a sprite. If you can provide a more complete picture of your project I would be happy to review it. Can you post the entire code file where you are doing your work? Or multiple files? On inspecting some of your samples further a few concerns in LoadRandomFood you are allocating an NSMutableArray without checking if RandomFood already has a value.
Something like this would be safer though note I am just doing a sanity check here. It would be more efficient to just fill in RandomFood once on init or elsewhere that is not going to be executed constantly.
-(void)LoadRandomFood
{
if (RandomFood)
{
[RandomFood release];
}
///I make my array here then and add CCSprites
RandomFood = [[NSMutableArray alloc]initWithObjects:
//cake,
RandomMuffin,
RandomMeat,
RandomCake,//
nil];//
int i = 0;
int count= [RandomFood count];
if (i < count)
{
int i = arc4random() % [RandomFood count];
myRandomSprite = (CCSprite *)[RandomFood objectAtIndex:i];
//waiterOnSCreen is a CCSprite added on the init
[waiterOnSCreen addChild:myRandomSprite];
myRandomSprite.position=ccp(290,220);
myRandomSprite.tag = RandomFoodTag;
}
}
In the case of the crash when adding a sprite are you sure the removeChildByTag call is being executed? Is it possible you are re-assigning the tag to a new sprite before deleting the old one? Have you stepped through the logic in the debugger? Again it would help to see a more complete code file here.
I had to make another array to access the sprite and delete it
NSMutableArray *_buffer = [NSMutableArray new];
[_buffer insertObject:myRandomSprite atIndex:0];
CCSprite *sprite = (CCSprite *)[_buffer objectAtIndex:0];
[sprite removeFromParentAndCleanup:YES];
I am adding sprites to a NSMutableArray like this:
NSMutableArray * movableSprites;
NSString *image = [images objectAtIndex:3];
CCSprite *sprite = [CCSprite spriteWithFile:image];
sprite.position = ccp(AREA_A2_X2 - (i * 56), AREA_A3A5A4_Y);
[self addChild:sprite];
[movableSprites addObject:sprite];
So far so good.
Now I am trying to detect collisions among them. The user is able to move the sprites around, but I want the sprites to be blocked by one another.
So, when I am working on the translation of them I want it to happen there. By the way, is it the best place to go for a collision detection?
- (void)panForTranslation:(CGPoint)translation {
if (selSprite) {
I intent to do the following in a loop:
CGRect rect1 = [SpriteUtilities positionRect:selSprite];
CGRect rect2 = [SpriteUtilities positionRect:EVERY_OTHER_SPRITE];
if (!CGRectIsNull(CGRectIntersection(rect1, rect2))) {
//handle collision
}
The thing is... I didn't find a NSMutableArray method to retrieve the sprite object.
Thank you for your help.
Ok... after a few more reading I got into this:
CCSprite *toCollide;
for (int i = 0; i < [movableSprites count]; i++){
toCollide = [movableSprites objectAtIndex:i];
...
Thanks anyway!! Hope it helps somebody else!
Is there any way to reduce the game framerate from 30 to 25 fps on the iPhone? I'm porting a Flash game created at 25 fps and exporting the sprites with this frame rate but animations are not shown as correctly as they should.
Any idea?
Try this instead, straight out of the box :
animation = [CCAnimation animationWithSpriteFrames:frames delay:.04];
with 40 ms delay, that should come real close to 25 fps (rendered animation) while the rest of the game is clocking full bore at 60 fps (if you don't have lag issues elsewhere)
I think that you can change your animation interval in your App Delegate with the following snippet in your didFinishLaunching method :
CCDirector *director = [CCDirector sharedDirector];
[director setAnimationInterval:1.0/25];
Hope this helps!
EDIT :
Could this link provide you more information about how to deal with that ?
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:best_practices
Well, at last the solution is by another way.
Kept the framerate to 1.0/60.0
What you need to do for animating the spritesheet slowest is to add the frame more than once to the animation array.
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = _spriteMetadata.spriteInitFrame; i <= _spriteMetadata.spriteEndFrame; ++i)
{
NSString *spriteFrameName = [NSString stringWithFormat:#"%#%#", _spriteMetadata.spriteBaseName, index];
for (int i=0; i<2; i++)
{
[walkAnimFrames addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteFrameName]];
}
}
It's not very orthodox but it works! :)
Thanks for your help Andy!
I am newer to cocos2d and preparing my demo game. I am moving a sprite from right to left using just a single image like a bird image moving from left to right. But I want to animate that sprite through various images so that it may look like a flying bird. I don't know how to accomplish that.
Here is my code:
CCSprite *target = [CCSprite spriteWithFile:#"Target.png" rect:CGRectMake(0, 0, 27, 40)]
id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(-target.contentSize.width/2, actualY)];
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)];
[target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
For Animating particular sprite You would require sprite-sheet to be there in your Resource. You can create the Sprite-sheet from eitherTexture Packer OR Zwoptex Tools which I normally use.
Next you can implement the Below Code
CCSpriteBatchNode *sheet = [CCSpriteBatchNode batchNodeWithFile:#"drawing1-i3.png"]; // Png File Name
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"drawing1-i3.plist"]; // Plist File Name
[self addChild:sheet];
//Generating the Animation
NSMutableArray *arr_anim =[NSMutableArray array];
for(int i=1; i<30; i++) // i< number of frames in the plist File Name
{
NSString *str_fileNm = [NSString stringWithFormat:#"drawing1%d.png",i];
CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:str_fileNm];
[arr_anim addObject:frame];
}
CCSprite *startAnim = [CCSprite spriteWithSpriteFrameName:#"drawing11.png"];
[startAnim setPosition:ccp(150,150)];
[self addChild:startAnim];
//Starting the Animation
CCAnimation *animation = [CCAnimation animationWithFrames:arr_anim delay:0.15f];
// id action =[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:YES]];
id action =[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];
[startAnim runAction:action];
I think it would help you for creating the Animations.
Use the CCAnimation class.
In particular, use methods like animationWithFrames: and supply your images as an array.
I am trying to preload an animation in the init method of my layer. I then call the animation if the screen is touched. The app crashes with no error message as soon as I touch the screen and seems it is to do with calling the preloaded animation. I would like to do it this way as it seems expensive to create the animation every time the screen is touched - which does seems to work though. Any tips greatly appreciated.
Sample Code:
In my header:
#interface Test : CCLayer {
NSMutableArray *wake;
CCSprite* ani;
CCAnimate *animate;
}
#end
In my implementation:
-(id) init {
if( (self=[super init])) {
// enable touches
self.isTouchEnabled = YES;
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"ani.plist" texture:[[CCTexture2D alloc] initWithImage:[UIImage imageNamed:#"ani.png"]]];
ani = [CCSprite spriteWithSpriteFrameName:#"ani1.png"]; //comes from .plist file
ani.anchorPoint=ccp(0,0);
ani.position = ccp(700,65);
[self addChild:ani z:30];
wake = [NSMutableArray array];
for(int i = 1; i <= 4; i++) {
[wake addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:#"ani%d.png",i]]];
}
animate = [CCAnimate actionWithAnimation:[CCAnimation animationWithFrames:wake delay:1.0f] restoreOriginalFrame:FALSE];
}
return self;
}
Handling the touch:
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// run the animation
[ani runAction:animate];
}
Animations in Cocos2d are not designed to be reused. You need to create a new one every time.
Problem solved by creating properties for the array and animation on the class using nonatomic,retain.
You only need to retain the animation but the array can be local.
self.myAnimation = [[CCAnimation animationWithFrames:myAniFramesArray delay:0.1f] retain];
Remember to make the property nonatomic, retain as stated by Chev and to release any objects you retain in the appropriate dealloc method.