Displaying score overlapping - iphone

I used cocos2d game tutorial from http://www.raywenderlich.com/25736/how-to-make-a-simple-iphone-game-with-cocos2d-2-x-tutorial After i add the score to scorelabel, the score increases but the previous score isn't getting removed and the new score gets added above the earlier score's label
code:
CGSize winSize = [[CCDirector sharedDirector] winSize];
CCLabelTTF * label1 = [CCLabelTTF labelWithString:#"_monsterdestroyed" fontName:#"Arial" fontSize:32];
score=score + 2;
[label1 setString:[NSString stringWithFormat:#"%d",score]];
label1.color = ccc3(0,0,0);
label1.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:label1];

I am guessing that you are doing all this in an update method, adding a label1 label at every update. You probably want an iVar in your .h file for the score label1 , initialize it in your init, as follows:
in .h
CCLabelTTF *label1;
in .m
-(id) init {
if (self = [super init]) {
// your existing code, add the following
CGSize winSize = [[CCDirector sharedDirector] winSize];
label1 = [CCLabelTTF labelWithString:#"0" fontName:#"Arial" fontSize:32];
label1.color = ccc3(0,0,0);
label1.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:label1];
}
}
// where you update the score
score = score + 2;
[label1 setSting:[NSString stringWithFormat:"%i", score];

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];
}

How to display the score in the game over layer in cocos2d

I've a problem when I try to show the final score in the Game Over Layer in a game in cocos2d. There's an algorithm that modify the value of my variable increment, that contains the points of the user and then the game shows them.
increment = increment + 50;
[pointLabel setString: [NSString stringWithFormat: #"Points: %i", increment]];
and then a function controls if the user has or not lives in his play
-(void)gameOver:(int)value punteggio:(id)punti{
if (value == 1) {
//WIN
}else if(value == 2){
if (life > 1) { // 1
life = life - 1;
for (CCSprite *spr in spriteLifeArray) {
if (life == spr.tag) {
[self removeChild:spr cleanup:YES];
}}}
else {
// LOSE
[...]
[[CCDirector sharedDirector] replaceScene:[GameOver node]];
}
}}
Then the GameOverLayer is called. This is the .h file
#interface GameOver : CCNode {
CGSize size;
CCLabelTTF *label1;
CCLabelTTF *label2;
CCLabelTTF *labelpnt;
CCLabelTTF *labelscore;
}
-(void)restart;
Here the .m file
#implementation GameOver
+(id) scene {
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
GameOver *layer = [GameOver node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init{
if( (self=[super init] )) {
size = [[CCDirector sharedDirector] winSize];
label1 = [CCLabelTTF labelWithString:#"Game Over" fontName:#"Marker Felt" fontSize:40];
label1.position = ccp(size.width/2 , size.height/2+20+50 );
labelpnt = [CCLabelTTF labelWithString:#"Punteggio" fontName:#"Marker Felt" fontSize:20];
labelpnt.position = ccp(size.width/2 , size.height/2+50-100 );
labelscore = [CCLabelTTF labelWithString:#"100" fontName:#"Marker Felt" fontSize:20];
[labelscore setString: [NSString stringWithFormat: #" 0 "]];
[labelscore setColor:ccc3(255, 1, 1)];
labelscore.position = ccp(size.width / 2, size.height/2+50-130);
label2 = [CCLabelTTF labelWithString:#"Ricomincia" fontName:#"Marker Felt" fontSize:25];
CCMenuItemLabel *back = [CCMenuItemLabel itemWithLabel:label2 target:self selector:#selector(restart)];
CCMenu *menu= [CCMenu menuWithItems:back, nil];
menu.position = ccp(size.width/2 , size.height/2-50+50);
[self addChild: label1];
[self addChild: labelpnt];
[self addChild: labelscore];
[self addChild: menu];
}
return self;
}
-(void) restart {
[[CCDirector sharedDirector] replaceScene:[HelloWorldLayer node]];
}
How can I show the final value of my int increment in the game over layer? How can I pass it throught the classes?
Use UserDefault. Here is code
//Save score in game screen
int highScore = 234;
[[NSUserDefaults standardUserDefaults] setInteger:12 forKey:#"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
//get score in game over
int highScore = [[NSUserDefaults standardUserDefaults] integerForKey:#"HighScore"];
NSString *score = [NSString stringWithFormat: #"%d", highScore];
CCLabelTTF *scoreLabel = [CCLabelTTF labelWithString:score fontName:#"Marker Felt" fontSize:40];
Hey in that Case You should take a separate layer for displaying the Score lives or whatever you want to display simultaneously.
In HUD Layer i.e Heads-Up Display class You should write some basic code to display a CCLabelBMFont to the screen that says "Your Score", “You Win” or “You Lose” and a button underneath that says “Restart”.
When the restart button is tapped, it creates a new instance of the ActionLayer switches to it.
Write a Score method scoreUpdate, this method will have the logic for the score calculation like whenever a bullet hit to monster and update it to the CCLabelBMFont label.
And then All you need to do just call that method.
Here is the one of the best tutorial for such requirement.
See

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

Constrain CCRenderTexture to top of screen when using CCCamera - Cocos2d

i have a "mini map" that I am using to show a portion of the background.
How can I constrain the CCRenderTexure to the top right corner of the screen? I am also using CCCamera to follow a sprite.
in init()
CGSize s = [[CCDirector sharedDirector] winSize];
minimap = [[CCRenderTexture renderTextureWithWidth:s.width * 1.5 height:s.height * 1.5] retain];
[minimap setPosition:ccp( s.width - ( s.width * kMinimapScaleFactor ) - 5, s.height - ( s.height * kMinimapScaleFactor ) - 5)];
[minimap begin];
[self visit];
[minimap end];
CCSprite *mms = [minimap sprite];
[mms setScale:kMinimapScaleFactor];
mms.scaleY *= -1;
mms.anchorPoint = ccp(0, 0);
[self addChild:minimap z:1 tag:1];
[self schedule:#selector(updateMinimap:) interval:1.0f];
Above init()
#define kMinimapScaleFactor 0.2
-(void) updateMinimap: (ccTime) dt
{
[minimap begin];
[self visit];
[minimap end];
}
in .h
CCRenderTexture *minimap;
#property(nonatomic, retain) CCRenderTexture *minimap;
Here is how I use CCCamera
id cameraMove = [CCFollow actionWithTarget:_ball];
[self runAction:cameraMove];
Anyone know?
Thanks
All you have to do is add it to the scene id
+ (id)scene
{
CCScene *scene = [CCScene node];
GameScene *layer = [GameScene node];
[scene addChild:layer];
CGSize s = [[CCDirector sharedDirector] winSize];
layer.player = [CCRenderTexture renderTextureWithWidth:s.width height:s.height];
CCSprite *mms = [layer.player sprite];
[mms setScale:kMinimapScaleFactor];
mms.scaleY *= -1;
mms.position = ccp(300, 400);
[scene addChild:layer.player z:2 tag:1];
[layer schedule:#selector(updateMinimap:) interval:1/30.0f];
layer._mini = [CCSprite spriteWithFile:#"minimap.png"];
layer._mini.position = ccp(405, 255);
layer._mini.opacity = 150;
[scene addChild:layer._mini];
return scene;
}

Countdown timer in cocos2d?

I'm trying to create a countdown timer in cocos2d, but I can not help and would like to resolve this problem, my code is below this, perhaps the logic is wrong but I can not fix.
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init] )) {
CCSprite *background = [CCSprite spriteWithFile:#"backgame.png"];
CGSize size = [[CCDirector sharedDirector] winSize];
[background setPosition:ccp(size.width/2, size.height/2)];
[self addChild: background];
[self schedule:#selector(countDown:)];
}
return self;
}
-(void)countDown:(ccTime)delta
{
CCLabel *text = [CCLabel labelWithString:#" "
fontName:#"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:text];
int countTime = 20;
while (countTime != 0) {
countTime -= 1;
[text setString:[NSString stringWithFormat:#"%i", countTime]];
}
}
Your int countTime = 20; is declaring itself every time to be 20. Also, your while loop will decrement the countTimer as fast as the system can update the CCLabel. If you're trying to do a real timer, you want it to decrement ONLY when countDown: is called. Not during a while-loop.
Try this:
#interface MyScene : CCLayer
{
CCLabel *_text;
}
#property (nonatomic, retain) int countTime;
#end
#implementation MyScene
#synthesize countTime = _countTime;
-(id) init {
if( (self=[super init] )) {
CCSprite *background = [CCSprite spriteWithFile:#"backgame.png"];
CGSize size = [[CCDirector sharedDirector] winSize];
[background setPosition:ccp(size.width/2, size.height/2)];
[self addChild: background];
_countTime = 20;
_text = [CCLabel labelWithString:[NSString stringWithFormat:#"%i", self.countTime]
fontName:#"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:_text];
[self schedule:#selector(countDown:) interval:0.5f];// 0.5second intervals
}
return self;
}
-(void)countDown:(ccTime)delta {
self.countTime--;
[_text setString:[NSString stringWithFormat:#"%i", self.countTime]];
if (self.countTime <= 0) {
[self unschedule:#selector(countDown:)];
}
}
#end
Your count allways becomes 20 in your countDown.
You should also move this to your init:
CCLabel *text = [CCLabel labelWithString:#" "
fontName:#"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:text];
Then you should use:
[self schedule:#selector(countDown:) interval:1.0f];
Then instead of using CCLabel you should use CCLabelBMFont. It's much faster :)