how to change image of moving ccsprite using timer - iphone

I have around 10 sprite of same image and these are moving, i want to change the image(2 images) of all sprite alternatively by using timer.
I am using following code but its not working for me
CCSprite *target = [CCSprite spriteWithFile:#"images1.png" rect:CGRectMake(0, 0, 120, 140)];
// Determine where to spawn the target along the Y axis
winSize = [[CCDirector sharedDirector] winSize];
int minY = target.contentSize.height/2;
int maxY = (winSize.height/2) - target.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) ;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
target.position = ccp(winSize.width + (target.contentSize.width/2), actualY);
[self addChild:target];
// Determine speed of the target
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
id delayTime1 = [CCDelayTime actionWithDuration:1.0f];
id calFun1 = [CCCallBlock actionWithBlock:^{
//HERE SET BLUE TEXTURE..
[target setTexture:[[CCSprite spriteWithFile:#"image1.png"]texture]];
}];
id delayTime2 = [CCDelayTime actionWithDuration:1.0f];
id calFun2 = [CCCallBlock actionWithBlock:^{
//HERE SET RED TEXTURE..
[target setTexture:[[CCSprite spriteWithFile:#"image2.png"]texture]];
}];
// Create the actions
id actionMove = [CCMoveTo actionWithDuration:actualDuration*2.5 position:ccp(-target.contentSize.width/2, actualY)];
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)];
id sequece = [CCSequence actions:delayTime1, calFun1, delayTime2, calFun2,actionMove, actionMoveDone, nil];
id repeate = [CCRepeatForever actionWithAction:sequece];
[target runAction:repeate];
But by using this code only one image is continuously showing on sprite. The image is not changing.

Try this
-(CCSpriteFrame *)getImageWithName:(NSString *)image{
CCSprite *sprite=[CCSprite spriteWithFile:image];
CCSpriteFrame *frame=[CCSpriteFrame frameWithTexture:sprite.texture rect:CGRectMake(0, 0, sprite.contentSize.width, sprite.contentSize.height)];
return frame;
}
Then
[target setDisplayFrame:[self getImageWithName:#"image1"]];
[target setDisplayFrame:[self getImageWithName:#"image2"]];

Related

Cocos2D - Layer background color not changing

I want to integrate cocos2d in one of my view. So, I have a normal view controller(MapEditorViewController) and a view, in my view controller, (I created a IBOutlet UIView *openGLView) in which I want cocos2d to be in. In my view controller, I have a method setupCocos2D :
- (void)setupCocos2D {
CCGLView *glView = [CCGLView viewWithFrame:self.openGLView.bounds
pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8
depthFormat:0 // GL_DEPTH_COMPONENT16_OES
];
glView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.openGLView insertSubview:glView atIndex:0];
[[CCDirector sharedDirector] setOpenGLView:glView];
CCScene *scene = [HelloWorldLayer scene];
[[CCDirector sharedDirector] runWithScene:scene];
}
setupCocos2D is called in viewDidLoad of the class MapEditorViewController.
I have a layer (HelloWorldLayer), which is basically the code in the tutorial of http://www.raywenderlich.com/25736/how-to-make-a-simple-iphone-game-with-cocos2d-2-x-tutorial
// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
- (void) addMonster {
CCSprite * monster = [CCSprite spriteWithFile:#"backbutton.png"];
// Determine where to spawn the monster along the Y axis
CGSize winSize = [CCDirector sharedDirector].winSize;
int minY = monster.contentSize.height / 2;
int maxY = winSize.height - monster.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;
// Create the monster slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
monster.position = ccp(winSize.width + monster.contentSize.width/2, actualY);
[self addChild:monster];
// Determine speed of the monster
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
// Create the actions
CCMoveTo * actionMove = [CCMoveTo actionWithDuration:actualDuration
position:ccp(-monster.contentSize.width/2, actualY)];
CCCallBlockN * actionMoveDone = [CCCallBlockN actionWithBlock:^(CCNode *node) {
[node removeFromParentAndCleanup:YES];
}];
[monster runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super's" return value
if( (self=[super initWithColor:ccc4(255,0,255,255)]) ) {
CGSize winSize = [CCDirector sharedDirector].winSize;
CCSprite *player = [CCSprite spriteWithFile:#"carteIntrouvable.png"];
player.position = ccp(player.contentSize.width/2, winSize.height/2);
[self addChild:player];
[self setIsTouchEnabled:YES];
[self schedule:#selector(gameLogic:) interval:1.0];
}
return self;
}
-(void)gameLogic:(ccTime)dt {
[self addMonster];
}
Now, I don't know what I'm doing wrong, the layer appears but it is black, even though I change the line initWithColor in -(id) init.
How can I change the layer's background color, because the code works if I don't integrate cocos2d with UIKit... ?
Alternative Solution: Add CCLayerColor to base layer.
-(void) onEnter
{
[super onEnter];
ccColor4B color = {255,255,0,255};
CCLayerColor *colorLayer = [CCLayerColor layerWithColor:color];
[self addChild:colorLayer z:LAST_LAYER_PLUS_1];
}

Cocos2d Random object from array not being called

I have created an array which stores either red, yellow, or green (3, 2, or 1) based on what the user hits. I want the code to choose a random number in the array and display the corresponding color on the screen. However, when the code runs, the program always chooses the last entered color and only shows that color.
Code:
-(void)CreateEnemy:(ccTime)dt{
CCSprite *Enemy;
int a;
if (colorArray != nil) {
a = arc4random()% [colorArray count];
}
int y = [[colorArray objectAtIndex:a] integerValue];
if (y == 1) {
Enemy = [CCSprite spriteWithFile:#"GreenBall.png"];
int x = arc4random()%320;
Enemy.position = ccp(x, 530);
id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
[Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)], nil]];
[enemyArray addObject:Enemy];
[self addChild:Enemy z:2 tag:1];
NSLog(#"Green Enemy Attack!!");
}
else if (y == 2) {
Enemy = [CCSprite spriteWithFile:#"YellowBall.png"];
int x = arc4random()%320;
Enemy.position = ccp(x, 530);
id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
[Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)], nil]];
[enemyArray addObject:Enemy];
[self addChild:Enemy z:2 tag:1];
NSLog(#"Yellow Enemy Attack!!");
}
else if (y == 3) {
Enemy = [CCSprite spriteWithFile:#"RedBall.png"];
int x = arc4random()%320;
Enemy.position = ccp(x, 530);
id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
[Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)], nil]];
[enemyArray addObject:Enemy];
[self addChild:Enemy z:2 tag:1];
NSLog(#"Red Enemy Attack!!");
}
}
Y should be a randomly chosen color, but it never is.
In:
if (colorArray != nil) {
a = arc4random()% [colorArray count];
}
int y = [[colorArray objectAtIndex:a] integerValue];
what is most likely happening is that [colorArray count] has not the value you expect it to have, so that arc4random only returns 0 (or a limited set of values).
If you add an NSLog trace just before calculating the value for a, you can assess the value for [colorArray count].

Adding a game over scene

I want to add this game over scene to this game that I am trying to do for my homework, and I seem to not have it where if you kill the target the game over scene will pop up. I tried putting my code in every line and see if it will finally work but no it didn't. So now I have to ask for some help.
. m file
- (void)addTarget10 {
Boss *target10 = nil;
if ((arc4random() % 2) == 0) {{
target10 = [WeakAndFastBoss9 boss9];
}} else {
target10 = [WeakAndFastBoss9 boss9];
}
[[SimpleAudioEngine sharedEngine] playEffect:#"lastboss.mp3"];
// Determine where to spawn the target along the Y axis
CGSize winSize = [[CCDirector sharedDirector] winSize];
int minY = target10.contentSize.height/2;
int maxY = winSize.height - target10.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
target10.position = ccp(winSize.width + (target10.contentSize.width/2), actualY);
[self addChild:target10 ];
// Determine speed of the target
int minDuration = target10.minMoveDuration;
int maxDuration = target10.maxMoveDuration;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
// Create the actions
id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(- target10.contentSize.width/2, actualY)];
id actionMoveDone = [CCCallFuncN actionWithTarget:self
selector:#selector(spriteMoveFinished9:)];
[target10 runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
target10.tag = 1;
[_targets addObject:target10];
}
-(void)gameLogicboss9:(ccTime)dt {
[self unschedule:_cmd];
[self addTarget10];
}
- (void)updateboss9:(ccTime)dt {
CGRect projectileRect = CGRectMake(projectile.position.x - (projectile.contentSize.width/2),
projectile.position.y - (projectile.contentSize.height/2),
projectile.contentSize.width,
projectile.contentSize.height);
BOOL bossHit = FALSE;
NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
for (CCSprite *target1 in _targets) {
CGRect target1Rect = CGRectMake(target1.position.x - (target1.contentSize.width/2),
target1.position.y - (target1.contentSize.height/2),
target1.contentSize.width,
target1.contentSize.height);
if (CGRectIntersectsRect(projectileRect, target1Rect)) {
[targetsToDelete addObject:target1];
bossHit = TRUE;
Boss *boss = (Boss *)target1;
boss.hp--;
if (boss.hp <= 0 ) {
[targetsToDelete addObject:target1];
}
break;
}
}
for (CCSprite *target in targetsToDelete) {
[_targets removeObject:target];
[self removeChild:target cleanup:YES];
_projectilesDestroyed++;
if (_projectilesDestroyed > 2) {
}
}
if (bossHit) {
//[projectilesToDelete addObject:projectile];
}
[targetsToDelete release];
}
-(void)spriteMoveFinishedboss9:(id)sender {
CCSprite *sprite = (CCSprite *)sender;
[self removeChild:sprite cleanup:YES];
if (sprite.tag == 1) { // target
[_targets removeObject:sprite];
} else if (sprite.tag == 2) { // projectile
[_projectiles removeObject:sprite];
} }
This the game over scene I want to add when target 10/ boss 9 is killed
GameOverScene *gameOverScene = [GameOverScene node];
[gameOverScene.layer.label setString:#"You Lose"];
[[CCDirector sharedDirector] replaceScene:gameOverScene];
Right now my other game over scene is when the sprite is moved passed screen.If you need me to answer any questions feel free to ask.
For scene replace you try this for your game code..
First Add this code to your GameOverScene class
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
GameOverScene *layer = [GameOverScene node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
Make your GameOverClass is subclass of CCLayer,
Than when You want to change scene do this
[[CCDirector sharedDirector] replaceScene:[GameOverScene scene]];
Ok, so you have to create a new scene. This can simple be done using File->New File and make it a subclass of NSObject. You then change the subclass to an CCLayer. As a test, you can just copy your code from the hello world layer. Next, just import the new class in your helloworld layer class and create a instance of it. Then in a method use [[CCDirector sharedDirector] replaceScene:sceneName];
You can use this site for more info, its very helpful, just read through it and you will find your answer:http://www.raywenderlich.com/352/how-to-make-a-simple-iphone-game-with-cocos2d-tutorial

i want my falling sprites to dissapear half way down the screen

im new to programming, i have been experimenting with cocos2d, heres the problem, i have made a simple game, device in portrait, it has falling sprites, and i want the sprite to disappear when the position of the top of the sprite < screen.height/2 how can this be done?
heres some code you may be interested in:
this is the falling sprite, it falls from the top of the screen to the bottom
-(void)addRock {
CCSprite *rock = [CCSprite spriteWithFile:#"rock.png"
rect:CGRectMake(0, 0, 27, 40)];
// Determine where to spawn the target along the X axis
CGSize winSize = [[CCDirector sharedDirector] winSize];
int minX = rock.contentSize.width/2;
int maxX = winSize.width - rock.contentSize.width/2;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;
// Create the target slightly off-screen along the right edge,
// and along a random position along the X axis as calculated above
rock.position = ccp(actualX, 500);
[self addChild:rock];
// Determine speed of the target
int actualDuration = spriteDuration;//speed of sprite
// Create the actions
id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(actualX,-winSize.height+ rock.contentSize.height)];
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)];
[rock runAction:[CCSequence actions:actionMove, nil]];
}
when the sprite move has finished
-(void)spriteMoveFinished:(id)sender {
CCSprite *sprite = (CCSprite *)sender;
[self removeChild:sprite cleanup:YES];
}
To fade your sprite out halfway of the Animation you can use CCSpawn to combine the falling animation with the fadeOut. But as you want it to fade out after a given time, you need to create a Sequence of CCDelayTime and CCFadeOut.
double fadeStart = 0.5;
id wait = [CCDelayTime actionWithDuration: actualDuration * fadeStart];
id fadeOut = [CCFadeOut actionWithDuration: actualDuration * (1.0 - fadeStart)];
id waitThenFade = [CCSequence actions: wait, fadeOut, nil];
id actionMove = ...;
id fullAnimation = [CCSpawn actions:actionMove, waitThenFade, nil];
[rock runAction:[CCSequence actions:fullAnimation, actionMoveDone, nil]];
In case you want the fading to start earlier or later you simply have to move the fadeStart value. 0 will start immediately, 1 will actually not fade, so better pick a value in between.
Maybe something like this?
CGSize size = [[CCDirector sharedDirector] winSize];
CCSprite* img = [[CCSprite alloc] initWithFile:#"yourSprite.png"];
img.position = ccp(size.width/2,size.height + img.boundingBox.size.height/2);
[img runAction:[CCSequence actions:
[CCMoveTo actionWithDuration:3 position:ccp(img.position.x,size.height/2 - img.boundingBox.size.height/2)],
[CCFadeOut actionWithDuration:1],
[CCCallFuncN actionWithTarget:nil selector:#selector(spriteMoveFinished:)],
nil]];

Cocos2d problem/question

I am making a game in Cocos2d. I want enemies to spawn on the right and left sides of the screen, and move to a random point on the screen, then repeat. Despite my efforts, I cannot figure it out. This should be relatively easy to answer, it should look like something out of one of Ray Wenderlich's tutorials. Some code would be nice. Thanks!
This is the code from ray Wanderlich tutorial..
[self schedule:#selector(addTarget) interval:2.0];
-(void)addTarget {
CCSprite *target = [CCSprite spriteWithFile:#"Target.jpg"
rect:CGRectMake(0, 0, 27, 40)]; //Creating Sprite and setting rect
// Determine where to spawn the target along the Y axis
CGSize winSize = [[CCDirector sharedDirector] winSize]; //Get the screensize
int minY = target.contentSize.height/2;
int maxY = winSize.height - target.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
target.position = ccp(winSize.width + (target.contentSize.width/2), actualY);
[self addChild:target];
// Determine speed of the target
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
// Create the actions
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]];
}
minY-->position at the bottom of the screen
maxY--->position at the top of the screen.
rangeY ---> the height of the screen.
actualY--->calculate the random point between bottom of the screen and top of the screen.
target.position --> setting random position for the sprite to move.
actualDuration --> getting random duration.so that the sprite moves in various time delay.
actionMove --> creating Move action.
actionMoveDone ---> After completing move action,calling spriteMoveFinished to remove sprites.