I have one image for background for all scenes,is it possible to write somewhere code for background so i don't have to write it on every scene I got and if it is then where I need to put it? For now i use this basic code :
background = [SKSpriteNode spriteNodeWithImageNamed:@"backMenu.png"];
titleBackground.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
titleBackground.size = self.frame.size;
titleBackground.zPosition = -10;
[self addChild:background];
If you have a code which is repeated among scenes, then you can create a BaseScene
and put that code there. So, everything shared between scenes , goes into BaseScene
.
BaseScene.h:
#import <SpriteKit/SpriteKit.h>
@interface BaseScene : SKScene
@end
BaseScene.m
#import "BaseScene.h"
@interface BaseScene()
@property(nonatomic, strong) SKSpriteNode *background;
@end
@implementation BaseScene
-(void)didMoveToView:(SKView *)view{
self.background = [SKSpriteNode spriteNodeWithImageNamed:@"backMenu"];
[self addChild:self.background];
}
@end
GameScene.h (now GameScene
inherits from BaseScene
, not from the SKScene
)
#import <SpriteKit/SpriteKit.h>
#import "BaseScene.h"
@interface GameScene : BaseScene
@end
GameScene.m
#import "GameScene.h"
@implementation GameScene
-(void)didMoveToView:(SKView *)view {
/* Setup your scene here */
[super didMoveToView:view];
}
@end
Finally, you call [super didMoveToView:view];
in every subclass of a BaseScene
which calls a didMoveToView:
of a BaseScene, which in turn adds background node to the current scene.