I know that my question might be stupid but I searched and I can't find why it's not working.
I create a CCLayer class BackgroundLayer with implementation below:
#import "BackgroundLayer.h"
#implementation BackgroundLayer
- (id)init {
if (self != nil) {
CCSprite *background = [CCSprite spriteWithFile:#"menu.png"];
background.anchorPoint = ccp(0, 0);
[self addChild:background z:-1];
NSLog(#"test");
}
return self;
}
#end
and I want to add it on main menu scene and I have:
#import "MainMenuScene.h"
#import "BackgroundLayer.h"
#implementation MainMenuScene
+ (id)scene {
CCScene *scene = [CCScene node];
BackgroundLayer *backgroundLayer = [BackgroundLayer node];
[scene addChild:backgroundLayer];
return scene;
}
- (id)init {
self = [super init];
if (self != nil) {
}
return self;
}
#end
My problem is that NSLog test appears but the background doesn't load. If I add the background on the init method of MainMenuScene it works... Shouldn't I suppose that the layer works this way?
Not sure if related but you forgot self = [super init]; in BackgroundLayer.
Try commenting out the anchor point line to see if the image shows up then.
Related
Hey folks I've being working around as follows. I get 2 layers, one's for control and the other's for game stuff. The problem is that the game's stucked ( the game's scene is refreshed and showed but it's out of control) when I trigerred a function for restart from my control layer. Have no idea where the problem is.
//restart function from input layer
......
-(id) init
{
if ((self = [super init]))
{......}
return self;
}
......
-(void)restart
{
GameScene* game = [GameScene sharedGameScene];
[game restartScene];
}
//gameLayer
......
static GameScene* instanceOfGameScene;
#implementation GameScene
+(GameScene*) sharedGameScene
{
if(instanceOfGameScene == nil)
instanceOfGameScene = [[self alloc]init];
return instanceOfGameScene;
}
+(id) scene
{
CCScene* scene = [CCScene node];
GameScene* layer = [GameScene node];
[scene addChild:layer z:0];
InputLayer* inputLayer = [InputLayer node];
[scene addChild:inputLayer z:1];
return scene;
}
-(void) restartScene
{
CCScene * newScene = [GameScene scene];
[[CCDirector sharedDirector] replaceScene:\
[CCTransitionFade transitionWithDuration:0.7f scene:newScene]];
}
......
[scene:newScene] does not seem to be valid ObjC syntax, does this even compile?
Anyway, you'll want to use newScene there and nothing else:
-(void) restartScene
{
CCScene * newScene = [GameScene scene];
[[CCDirector sharedDirector] replaceScene:newScene];
}
firstly i would like to apologise for being a complete novice but I have researched the web and can not find a solution to my current problem.
I have 3 objects (sprites) that i have set up individually with switch statements and want to use my main gameplay layer to change their states randomly to an animation that i have already defined in the objects individual header and implementation files.
I have set up a self schedule updater and arc4random method that works but it will not change the state of the object, as it only calls the CCLOG that I have also included in the statement.
I have listed to code below and i know it is a bit of a mess but still very much in my first steps of being a beginner, if anyone can point me in the right direction (that's if i have explained this in a way you can understand!) I would be very grateful.
Thanks in advance for even looking at this question.
//-------------------below is my gameplaylayer header file---------//
// GamePlayLayer.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "CCLayer.h"
#import "SneakyJoystick.h"
#import "SneakyButton.h"
#import "SneakyButtonSkinnedBase.h"
#import "SneakyJoystickSkinnedBase.h"
#import "Constants.h"
#import "CommonProtocols.h"
#import "TBT.h"
#import "MBT.h"
#import "BBT.h"
#import "BC.h"
#import "GameCharacter.h"
#import <stdlib.h>
#interface GamePlayLayer : CCLayer <GamePlayLayerDelegate> {
CCSprite *vikingSprite;
SneakyJoystick *leftJoystick;
SneakyButton *jumpButton;
SneakyButton *attackButton;
CCSpriteBatchNode *sceneSpriteBatchNode;
}
#property (readwrite) CharacterStates characterState;
-(void)changeState:(CharacterStates)newState;
-(void)addEnemy;
#end
//---------------------Below is my gameplaylayer implementation file-------------//
// GamePlayLayer.m
#import "GamePlayLayer.h"
#implementation GamePlayLayer
#synthesize characterState;
-(void) dealloc {
[leftJoystick release];
[jumpButton release];
[attackButton release];
[super dealloc];
}
-(void)initJoystickAndButtons {
CGSize screenSize = [CCDirector sharedDirector].winSize;
//---DELETED MOST OF THE ABOVE METHOD AS NOT NEEDED FOR THIS QUESTION----//
-(void) update:(ccTime)deltaTime {
CCArray *listOfGameObjects =
[sceneSpriteBatchNode children];
for (GameCharacter *tempChar in listOfGameObjects) {
[tempChar updateStateWithDeltaTime:deltaTime andListOfGameObjects:listOfGameObjects];
}
}
-(void) createObjectOfType: (GameObjectType)objectType
withHealth:(int)initialHealth atLocation:(CGPoint)spawnLocation withZValue:(int)ZValue {
if (objectType == kEnemyType1BT) {
CCLOG(#"creating the 1BT");
TBT *tBT = [[TBT alloc] initWithSpriteFrameName:#"BT_anim_1.png"];
[tBT setCharacterHealth:initialHealth];
[tBT setPosition:spawnLocation];
[sceneSpriteBatchNode addChild:tBT
z:ZValue
tag:k1BTtagValue];
[tBT release];}
if (objectType == kEnemyType3BT){
CCLOG(#"creating the radar enemy");
BBT *bBT = [[BBT alloc] initWithSpriteFrameName:#"BT_anim_1.png"];
[bBT setCharacterHealth:initialHealth];
[bBT setPosition:spawnLocation];
[sceneSpriteBatchNode addChild:bBT
z:ZValue
tag:k3BTtagValue];
[bBT release];
}
if (objectType == kEnemyType2BT){
CCLOG(#"creating the radar enemy");
MBT *mBT = [[MBT alloc] initWithSpriteFrameName:#"BT_anim_1.png"];
[mBT setCharacterHealth:initialHealth];
[mBT setPosition:spawnLocation];
[sceneSpriteBatchNode addChild:mBT
z:ZValue
tag:k2BTtagValue];
[mBT release];
}
}
//--PROBLEM I HAVE IS BELOW--//
-(void)addEnemy {
int x = (arc4random() % 3);
TBT *tBT = (TBT*)
[sceneSpriteBatchNode getChildByTag:kEnemyType1BT];
//--Just using one object(sprite) to begin with--//
if (x>0) {
CCLOG(#"RANDOM KSTATETEST!!!!!!");
[tBT changeState:kStatetest]; <---it is not changing state to kStatetest
}
-(id)init {
self = [super init];
if (self !=nil) {
CGSize screenSize = [CCDirector sharedDirector]. winSize;
self.TouchEnabled = YES;
srandom(time(NULL));
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[[CCSpriteFrameCache sharedSpriteFrameCache]
addSpriteFramesWithFile:#"scene1atlas.plist"]; // 1
sceneSpriteBatchNode =
[CCSpriteBatchNode batchNodeWithFile:#"scene1atlas.png"]; // 2
} else {
[[CCSpriteFrameCache sharedSpriteFrameCache]
addSpriteFramesWithFile:#"scene1atlasiPhone.plist"]; // 1
sceneSpriteBatchNode =
[CCSpriteBatchNode batchNodeWithFile:#"scene1atlasiPhone.png"];// 2
}
[self addChild:sceneSpriteBatchNode z:0]; // 3
[self initJoystickAndButtons]; // 4
BC *viking = [[BC alloc]
initWithSpriteFrame:[[CCSpriteFrameCache
sharedSpriteFrameCache]
spriteFrameByName:#"BCmoving_anim_1.png"]];
//[viking setJoystick:leftJoystick];
[viking setJumpButton:jumpButton];
[viking setAttackButton:attackButton];
[viking setPosition:ccp(screenSize.width * 0.19f,
screenSize.height * 0.19f)];
[viking setCharacterHealth:3];
[sceneSpriteBatchNode
addChild:viking
z:kVikingSpriteZValue
tag:kVikingSpriteTagValue]; heatlh is set to 100
[self schedule:#selector(addEnemy) interval:1.0f];
[self createObjectOfType:kEnemyType1BT withHealth:3 atLocation:ccp(screenSize.width * 0.0439f, screenSize.height * 0.822f) withZValue:10];
[self createObjectOfType:kEnemyType3BT withHealth:3 atLocation:ccp(screenSize.width * 0.0439f, screenSize.height * 0.45f) withZValue:10];
[self createObjectOfType:kEnemyType2BT withHealth:3 atLocation:ccp(screenSize.width * 0.0439f, screenSize.height * 0.638f) withZValue:10];
//Sets up the schedular call that will fire the update method in GamePlayLayer.m every frame.
[self scheduleUpdate];
}
return self;
}
#end
//----------------- below is one of my objects header files--------------//
#import <Foundation/Foundation.h>
#import "GameCharacter.h"
#interface TBT : GameCharacter{
CCAnimation *tiltingAnim;
CCAnimation *transmittingAnim;
CCAnimation *loseLifeAnim;
CCAnimation *throwingAnim;
CCAnimation *afterThrowingAnim;
CCAnimation *shootPhaserAnim;
GameCharacter *vikingCharacter;
id <GamePlayLayerDelegate> delegate;
}
#property (nonatomic,assign) id <GamePlayLayerDelegate> delegate;
#property (nonatomic, retain) CCAnimation *tiltingAnim;
#property (nonatomic, retain) CCAnimation *transmittingAnim;
//#property (nonatomic, retain) CCAnimation *takingAHitAnim;
#property (nonatomic, retain) CCAnimation *loseLifeAnim;
#property (nonatomic, retain) CCAnimation *throwingAnim;
#property (nonatomic,retain) CCAnimation *afterThrowingAnim;
#property (nonatomic,retain) CCAnimation *shootPhaserAnim;
-(void)initAnimations;
#end
//-----------------below is the .m file for one of my objects--------------//
#import "TBT.h"
#implementation TBT
#synthesize delegate;
#synthesize tiltingAnim;
#synthesize transmittingAnim;
#synthesize loseLifeAnim;
#synthesize throwingAnim;
#synthesize afterThrowingAnim;
#synthesize shootPhaserAnim;
-(void) dealloc {
delegate = nil;
[tiltingAnim release];
[transmittingAnim release];
[loseLifeAnim release];
[throwingAnim release];
[afterThrowingAnim release];
[shootPhaserAnim release];
[super dealloc];
}
-(void)shootPhaser {
CGPoint phaserFiringPosition;
PhaserDirection phaserDir;
CGRect boundingBox = [self boundingBox];
CGPoint position = [self position];
float xPosition = position.x + boundingBox.size.width * 0.542f;
float yPosition = position.y + boundingBox.size.height * 0.25f;
if ([self flipX]) {
CCLOG(#"TBT Facing right, Firing to the right");
phaserDir = kDirectionRight;
} else {
CCLOG(#"TBT Facing left, Firing to the left");
xPosition = xPosition * -1.0f;
phaserDir = kDirectionLeft;
}
phaserFiringPosition = ccp(xPosition, yPosition);
[delegate createPhaserWithDirection:phaserDir andPosition:phaserFiringPosition];
}
-(void)changeState:(CharacterStates)newState {
[self stopAllActions];
id action = nil;
[self setCharacterState:newState];
switch (newState) {
case kStatespawning:
CCLOG(#"TBT->Changing State to Spwaning");
[self setDisplayFrame:
[[CCSpriteFrameCache sharedSpriteFrameCache]
spriteFrameByName:#"BT_anim_1.png"]];
break;
case kStateIdle:
CCLOG(#"TBT->schaning state to idle");
[self setDisplayFrame:
[[CCSpriteFrameCache sharedSpriteFrameCache]
spriteFrameByName:#"BT_anim_1.png"]];
break;
case kStatetest:
CCLOG(#"TBT->Changing State to test");
action = [CCSequence actions : [CCDelayTime actionWithDuration:1.5f],[CCAnimate actionWithAnimation:transmittingAnim], nil];
break;
default:
CCLOG(#"unhandled state %d in TBT", newState);
break;
}
if (action !=nil) {
[self runAction:action];
}
}
-(void)updateStateWithDeltaTime: (ccTime)deltaTime andListOfGameObjects:(CCArray*)listOfGameObjects {
if (characterState == kStateDead)
return;
if ((([self numberOfRunningActions] == 0) && (characterState != kStateDead)) ) {
CCLOG(#"TBT Going to Idle");
[self changeState:kStateIdle];
return;
}
}
-(void)initAnimations {
[self setTiltingAnim:[self loadPlistForAnimationWithName:#"tiltingAnim" andClassName:NSStringFromClass([self class])]];
[self setTransmittingAnim:[self loadPlistForAnimationWithName:#"transmittingAnim" andClassName:NSStringFromClass([self class])]];
}
-(id) initWithSpriteFrameName:(NSString*)frameName{
if ((self=[super init])) {
if ((self = [super initWithSpriteFrameName:frameName])) {
CCLOG(#"### TBT initialized");
[self initAnimations];
characterHealth = 3.0f;
gameObjectType = kEnemyType1BT;
[self changeState:kStatespawning];
}}
return self;
}
#end
Finally found out that all I needed was to add the following code to my TBT gameCharacters-(void)updateStateWithDeltaTime: method...
if (characterState == kStateTest) {
if (characterState != kStateTest) {
[self changeState:kStateTest];
return;
}
now it works fine.
Thanks again to Mikael for trying to help me.
I am tying to dynamically change my background color on the fly using an NSColorWell. I am using cocos2d framework for desktop.
I have a GLView that shows the cocos2d window and I have a NSColorwell off to the side. When I click on the color well color, I want the background to change to that color ‘on-the-fly’ so to speak.
I have all my variables in one class called settings. And my AppDeletgate has the IBActions for the NSColorWell. And the Cocos2D GLview lives in the HelloWorldLayer.
When ever I chose a color in the NSColorWell I get an exception thrown. Any idea why?
Forgive the code dump but I wanted you all to be able to see exactly what I was doing. I have tried many different methods of implementing this.
AppDelegate.h
#import "cocos2d.h"
#interface AnimatorAppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow *window_;
MacGLView *glView_;
#property (assign) IBOutlet NSWindow *window;
#property (assign) IBOutlet MacGLView *glView;
- (IBAction)bgColorWell:(id)sender;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "HelloWorldLayer.h"
#import "Settings.h"
#implementation AnimatorAppDelegate
#synthesize window=window_, glView=glView_;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CCDirectorMac *director = (CCDirectorMac*) [CCDirector sharedDirector];
[director setDisplayFPS:YES];
[director setOpenGLView:glView_];
[director setResizeMode:kCCDirectorResize_AutoScale];
[window_ setAcceptsMouseMovedEvents:NO];
[director runWithScene:[HelloWorldLayer scene]];
}
#pragma mark AppDelegate - IBActions
- (IBAction)toggleFullScreen: (id)sender
{
CCDirectorMac *director = (CCDirectorMac*) [CCDirector sharedDirector];
[director setFullScreen: ! [director isFullScreen] ];
}
- (IBAction)bgColorWell:(id)sender {
NSLog(#"Color Well %#", [sender color]);
HelloWorldLayer *layer = [[HelloWorldLayer alloc] init];
[layer setBackgroundColorForLayer:[sender color]];
}
#end
Settings.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#interface Settings : NSObject {
NSColor *_backgroundColor;
}
+ (Settings *) sharedSettings;
- (NSColor *) returnBackgroundColor;
- (void) setBackgroundColor : (NSColor *)c;
#end
Settings.m
#import "Settings.h"
#implementation Settings
static Settings * _sharedSettings;
- (id) init {
if (self = [super init]){
//_backgroundColor = [NSColor colorWithDeviceRed:102/255.0f green:205/255.0f blue:170/255.0f alpha:1.0];
_backgroundColor = [NSColor blueColor];
}
return self;
}
+ (Settings *) sharedSettings {
if (!_sharedSettings) {
_sharedSettings = [[Settings alloc] init];
}
return _sharedSettings;
}
- (NSColor *) returnBackgroundColor {
return _backgroundColor;
}
- (void) setBackgroundColor : (NSColor *)c {
_backgroundColor = c;
}
#end
HelloWorldLayer.h
#import "cocos2d.h"
#import "Settings.h"
// HelloWorldLayer
#interface HelloWorldLayer : CCLayer
{
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
- (void) setBackgroundColorForLayer : (id) sender;
#end
HelloWorldLayer.m
// Import the interfaces
#import "AppDelegate.h"
#import "HelloWorldLayer.h"
#import "Settings.h"
// HelloWorldLayer implementation
#implementation HelloWorldLayer
+(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;
}
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {
CGSize winSize = [[CCDirector sharedDirector] winSize];
}
return self;
}
- (void) setBackgroundColorForLayer : (id) sender {
Settings *mySettings = [Settings sharedSettings];
float red = [mySettings returnBackgroundColor].redComponent * 255;
float green = [mySettings returnBackgroundColor].greenComponent * 255;
float blue = [mySettings returnBackgroundColor].blueComponent * 255;
CCLayerColor* colorLayer = [CCLayerColor layerWithColor:ccc4(red, green, blue, 255)];
[self addChild:colorLayer z:0];
NSLog(#"Red color: %f", red);
NSLog(#"Green color: %f", green);
NSLog(#"Blue color: %f", blue);
//[self setBackgroundColorForLayer:sender];
NSLog(#"This Background color is %#" , [mySettings returnBackgroundColor]);
}
I want to add one cclayer on top of another.
I have tried this by using following code
+(id) scene
{
CCScene *scene = [CCScene node];
GameScreen *layer = [GameScreen node];
[scene addChild: layer];
GameScreen *newLayer=[GameScreen node];
[scene addChild:newLayer];
return scene;
}
but may be there are some mistakes, cuz when i tried to add something on newLayer ,it says using undeclared variable even when ideclared that in .h file also.
Can you please help me with detail code?
Instead of doing this in the "scene" class method, add the "new" CCLayer in the -(id)init{} method:
-(id) init {
self = [super init];
if (self) {
GameScreen *newLayer=[GameScreen node];
[self addChild:newLayer];
//Other code
} return self;
}
i am working on very first tutorial on cocos2d understanding basic concept.I am trying to change background color from default(black) to white.here is my code:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#interface GameScene : CCLayerColor {
CCSprite *player;
}
+(id) scene;
#end
and implementation goes here:
#import "GameScene.h"
#implementation GameScene
+(id) scene
{
CCScene *scene = [CCScene node];
CCLayer *layer = [CCLayer node];
[scene addChild:layer];
return scene;
}
-(id) init
{
if ((self=[super initWithColor:ccc4(255, 255, 255, 255)])) {
self.isAccelerometerEnabled=YES;
player= [CCSprite spriteWithFile:#"Icon-72.png"];
CGSize screenSize=[[CCDirector sharedDirector] winSize];
float imageHeight=[player texture].contentSize.height;
player.position=CGPointMake(screenSize.width/2, imageHeight/2);
[self addChild:player z:0 tag:123];
}
return self;
}
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
CGPoint pos=player.position;
pos.x+=acceleration.x*10;
player.position=pos;
}
- (void)dealloc {
[super dealloc];
}
#end
any suggestion? thanks
CCDirectory only takes CCScenes. So most likely the black screen you experience is not a faulty CCColorLayer, but simply the blank stage.
Subclass CCScene as GameScene, then add a CCLayerColor to that with your desired color, as well as your player. Then call [[CCDirector sharedDirector] runWithScene:gameScene].