artG
artG

Reputation: 235

One background image for all scenes objective c

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

Upvotes: 0

Views: 277

Answers (2)

Whirlwind
Whirlwind

Reputation: 13665

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.

Upvotes: 1

Mobile Ben
Mobile Ben

Reputation: 7331

An SKNode can only belong to one scene. So you will need to add the SKSpriteNode for the background to every scene.

Assuming you will be creating and destroying scenes as needed what you should do is maintain a reference to the SKTexture for the background.

Then in that case, create the SKSpriteNode when needed

background = [SKSpriteNode spriteNodeWithTexture:backgroundTex];

You would then add this based on your application to the scene.

In the above example, backgroundTex would be your reference. You should stash it in some object which maintains it. If you have a texture manager, you should be able to ask for the already allocated texture by reference name.

Upvotes: 0

Related Questions