Basically I have four scenes and on viewcontroller, I want to detect in which scene am I because, I have background music in viewcontroller, and I want to pause music in some Scenes. I found how to detect scenes in viewController, but it was in swift, and I know only basics of objective c.
Edited
SKView *skView =(SKView *)self.view;
TitleScene *sceneTitle = [TitleScene sceneWithSize:self.view.bounds.size];
BonusScene *sceneBonus = [BonusScene sceneWithSize:self.view.bounds.size];
GameScene *sceneGame = [GameScene sceneWithSize:self.view.bounds.size];
DifficultScene *sceneDifficult = [DifficultScene sceneWithSize:self.view.bounds.size];
if(skView){
if(sceneTitle){
NSLog(#"Iam in sceneTitle");
}
if(sceneGame){
NSLog(#"Iam in sceneGame");
}
if(sceneDifficult){
NSLog(#"Iam in sceneDifficult");
}
if(sceneBonus){
NSLog(#"Iam in sceneBonus");
}
else{
NSLog(#"else");
}
}
now, when start app, it runs through every if statement once,even when Iam only in TitleScene. What did wrong?
Give each scene a name, then in your viewcontroller class, just do
SWIFT:
if let skView = view as? SKView, let scene = skView.scene
{
switch(scene.name)
{
case "name1":
default:()
}
}
else
{
//Something is wrong, we do not have an SKView or a SKScene
}
Objective C:
SKView *view = (SKView*)self.view ;
if(view)
{
SKScene *scene = view.scene;
if(scene)
{
NSString *name = scene.name;
//compare names here
}
}
Related
Since xCode was updated to version 6.0, the default method for SpriteKit in "GameScene" (the default scene created) changes to:
-(void) didMoveToView:(SKView *) view {
/* Scene set up in here */
}
as opposed to the older method:
-(id) initWithSize:(CGSize) size {
if (self = [super initWithSize:size]{
/* Scene set up in here */
}
}
I understand that the new method (as with the changes in the view controller) is used to help manage the import from the .sks file that is new in xCode 6. However, I was curious if I didn't want to use the new "storyboard"-type format that is the .sks file, should I still use the new method? Or should I change the method back to the initWithSize method and just delete the .sks file?
Init methods should be used for initializing but keep in mind that inside init, view is always nil. So any code that needs the view has to be moved to didMoveToView method (it's called immediately after a scene is presented by a view).
About initWithSize in Xcode 6... By default, scene is loaded from .sks file. Because of this, initWithSize is never called actually. initWithCoder is called instead:
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
// do stuff
}
return self;
}
So initializing anything inside initWithSize won't have any effect. If you decide to delete .sks file and create a scene in "old" way, you can do something like this in view controller:
- (void)viewDidLoad
{
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = YES;
// Create and configure the scene.
GameScene *scene = [GameScene sceneWithSize:self.view.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
// Present the scene.
[skView presentScene:scene];
}
After that, you can use initWithSize for initialization.
Note that in viewDidLoad the final size of a view may not be known yet, and using viewWillLayoutSubviews instead could be a right choice. Read more here.
And proper implementation of viewWillLayoutSubviews for scene initialization purpose would be:
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
// Configure the view.
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = YES;
//viewWillLayoutSubviews can be called multiple times (read about this in docs ) so we have to check if the scene is already created
if(!skView.scene){
// Create and configure the scene.
GameScene *scene = [GameScene sceneWithSize:self.view.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
// Present the scene.
[skView presentScene:scene];
}
}
Swift code:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.showsPhysics = true
skView.showsDrawCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
if(skView.scene == nil){
scene.scaleMode = .AspectFill
scene.size = skView.bounds.size
skView.presentScene(scene)
}
}
}
I think that, for all intents and purposes, there isn't much of a difference between the two methods when it comes to actually setting up your scene and using it. (initWithSize is called when the scene is initialized, while didMoveToView is always called right when the scene is presented by the view). I guess if you really prefer to see the initialization then you could just use the init method without any trouble at all.
Regarding the .sks file:
take a look at your view controller implementation file. Right above the v.controller's methods you'll see:
#implementation SKScene (Unarchive)
+ (instancetype)unarchiveFromFile:(NSString *)file {
/* Retrieve scene file path from the application bundle */
NSString *nodePath = [[NSBundle mainBundle] pathForResource:fileofType:#"sks"];
/* Unarchive the file to an SKScene object */
NSData *data = [NSData dataWithContentsOfFile:nodePath
options:NSDataReadingMappedIfSafe
error:nil];
NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[arch setClass:self forClassName:#"SKScene"];
SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
[arch finishDecoding];
return scene;
}
#end
This is the part that handles the sks. Using the file is totally optional, you aren't forced to do it and it really has no impact on you setting up your scene. However, if you do want to work with it, then you'll find that you'll need to work with this code snippet.
Both options are correct. Said that, the init method is not actually the same than the didMoveToView: method, as this last one will be called once the SKScene is presented in a SKView.
I am having an issue getting the correct coordinates from a UITouch on an SKScene after the SKScene is presented the second time. I've written a simplified app to demonstrate the issue located here:
https://github.com/JenDobson/SKSceneCoordinatesIssue
In this simplified app there is 1 scene. The scene has a single SKNode. When the scene is touched, if the UITouch location intersects with the SKNode, the touchesEnded:withEvent method calls back to the ViewController to present the scene a second time. But when the scene is presented a second time, when I attempt to touch the SKNode, the coordinates of the UITouch are reversed (i.e. the x value reports the y value and vice versa). They thus don't intersect with the SKNode, and the scene is not presented again. (If I touch at the location on the screen that is the SKNode's position reflected over the line x=y, then I can get the scene to be presented again.)
I've tried playing around with "ViewWillLayoutSubviews", but in this sample app the view is only loaded once, so I believe that ViewWillLayoutSubviews is not called repeatedly and therefore cannot affect the scene coordinates.
To illustrate the issue, here is the output from touchesEnded:withEvent the first time the scene is presented:
2014-07-21 17:57:06.908 TestTouchCoordinatesInSKScene[5476:60b] scene frame size:1024.000000,768.000000
2014-07-21 17:57:06.911 TestTouchCoordinatesInSKScene[5476:60b] location:685.000000,105.500000
2014-07-21 17:57:06.912 TestTouchCoordinatesInSKScene[5476:60b] navNode Position:700.000000,100.000000
And here is the output from touchesEnded:withEvent the second time the scene is presented:
2014-07-21 17:57:14.724 TestTouchCoordinatesInSKScene[5476:60b] scene frame size:1024.000000,768.000000
2014-07-21 17:57:14.725 TestTouchCoordinatesInSKScene[5476:60b] location:107.000000,632.500000
2014-07-21 17:57:14.726 TestTouchCoordinatesInSKScene[5476:60b] navNode Position:700.000000,100.000000
Note that "location" has the x- and y- coordinates reversed for the second listing.
Below is what I think the relevant code is.
In "MyViewController.m"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
SKView* skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
CGSize contentSize = CGSizeMake(skView.bounds.size.width,skView.bounds.size.height);
_mainMenuScene = [MyMainMenuScene sceneWithSize:contentSize];
_mainMenuScene.controller = self;
_mainMenuScene.scaleMode = SKSceneScaleModeAspectFill;
[skView presentScene:_mainMenuScene];
}
-(void)loadView
{
CGRect viewFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
SKView* view = [[SKView alloc] initWithFrame:viewFrame];
self.view = view;
}
-(void)returnToMainMenu
{
[(SKView*)self.view presentScene:_mainMenuScene transition:[SKTransition moveInWithDirection:SKTransitionDirectionRight duration:.3]];
}
#end
In "MyMainMenuScene.m"
-(CGPoint)navNodePosition
{
return CGPointMake(700,100);
}
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
_navNode = [SKLabelNode node];
_navNode.position = [self navNodePosition];
_navNode.text = #"Return to Main Menu";
_setupLabel.fontColor = [UIColor whiteColor];
_setupLabel.fontSize = 24;
[self addChild:_navNode];
}
return self;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
BOOL shouldSegueToMainMenu = NO;
NSLog(#"scene frame size:%f,%f",self.frame.size.width,self.frame.size.height);
for (UITouch* touch in touches) {
CGPoint touchLocation = [touch locationInNode:self];
NSLog(#"location:%f,%f",touchLocation.x,touchLocation.y);
NSLog(#"navNode Position:%f,%f",self.navNode.position.x,self.navNode.position.y);
if ([self.navNode containsPoint:touchLocation]) {
shouldSegueToMainMenu = YES;
break;
}
}
if (shouldSegueToMainMenu)
{
[self.controller returnToMainMenu];
}
}
Thanks very much!
After playing around more, I believe this is a bug in the SKView method presentScene:transition. In the returnToMainMenu method of MyViewController, if I use the plain old presentScene method rather than presentScene:transition, the problem goes away. I've filed this with Apple as bug 17770198.
I'm using the root viewcontroller to display a couple of labels to keep track of scores etc, which is working fine. However, the root viewcontroller is not responding to messages from the scene right away when the scene is loaded.
The situation is this: UIViewController presents SKView where I initialize MyScene on top of that (normal SpriteKit stuff). Immediately in MyScene I load the level from a json-file, which contains the number of possible points on that specific level. When the level is done loaded, I try to send the number of possible points back to my root viewcontroller, so it can display it in a label.
I've tried setting a property myScene.mainViewController = self from the viewWillLayoutSubviews on ViewController, and then just [self.mainViewController setInitialScore:_bgLayer.maxScore];, but the method setInitialScore never fires. I've also tried using the NSNotificationCenter, but this does not work either.
However, I call a method in self.mainViewController whenever the player collects a point (which happens a little bit later), and that works fine. So the problems seems to be that the ViewController is not done loading or something, so it doesn't respond right away.
How could I solve this?
EDIT 1:
Here's some code by request:
ViewController.m
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
SKView *skView = (SKView *)self.view;
if (!skView.scene) {
skView.showsFPS = YES;
skView.showsNodeCount = YES;
// Create and configure the scene.
MyScene* scene = [MyScene sceneWithSize:skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
scene.mainViewController = self;
// Present the scene.
[skView presentScene:scene];
self.numLives = bStartNumLives;
self.score = 0;
[self resetLabels];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(setInitialRings:) name:#"setInitialRings" object:nil];
}
}
- (void)setInitialRings:(NSNotification *)notification {
NSLog(#"Initial rings set");
NSDictionary *userInfo = [notification userInfo];
NSInteger rings = [(NSNumber *)[userInfo objectForKey:#"rings"] integerValue];
self.numRings = rings;
[self resetLabels];
}
MyScene.m
- (void)createWorld {
_bgLayer = [self createScenery];
NSLog(#"world created setting initial rings");
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:_bgLayer.numRings] forKey:#"rings"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"setInitialRings" object:userInfo];
_worldNode = [SKNode node];
[_worldNode addChild:_bgLayer];
[self addChild:_worldNode];
self.anchorPoint = CGPointMake(0.5, 0.5);
_worldNode.position = CGPointMake(-_bgLayer.layerSize.width / 2, -_bgLayer.layerSize.height / 2);
}
As you can see from this snippet of code, I'm trying to use the NSNotificationCenter. I've also tried calling [self.mainViewController setInitialRings:_bgLayer.numRings]; manually (but changing the setInitialRings-method to take an integer instead of a notification).
I am currently working on an Cocos2d-x, which uses native UI (UIKit Framework) besides the Game.
This is my actual workflow:
When I start the game every things works well. I can even restart the game by reinitializing the scene, but I can't pop the UIViewController with my CCEAGLView and push it again on the top.
When I do this I get a scene without any movement.
Here's my opens the scene:
if (cocos2d::Director::getInstance()->getRunningScene() && [[self.view.subviews firstObject] isKindOfClass:[CCEAGLView class]]) {
//Restart scene without popping ViewController
//Works well
auto beam = GrowingBeam::createLayer();
auto scene = beam->getScene();
beam->_self = (__bridge void*) self;
cocos2d::Director::getInstance()->replaceScene(scene);
}else {
if (cocos2d::Director::getInstance()->getRunningScene()) {
//Restart scene after View Controller has been popped
// DOESN'T WORK !!
auto beam = GrowingBeam::createLayer();
auto scene = beam->getScene();
beam->_self = (__bridge void*) self;
[self.view insertSubview:(__bridge CCEAGLView *) cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView() atIndex:0];
cocos2d::Director::getInstance()->replaceScene(scene);
scene->resume();
cocos2d::Director::getInstance()->resume();
}else {
//Start Scene for the first time
//Works well
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [UIScreen mainScreen].bounds
pixelFormat: kEAGLColorFormatRGBA8
depthFormat: GL_DEPTH24_STENCIL8_OES
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0];
// IMPORTANT: Setting the GLView should be done after creating the RootViewController
auto gl2view = cocos2d::GLView::createWithEAGLView((__bridge void*)eaglView);
cocos2d::Director::getInstance()->setOpenGLView(gl2view);
[self.view insertSubview:eaglView atIndex:0];
auto beam = GrowingBeam::createLayer();
auto scene = beam->getScene();
beam->_self = (__bridge void*) self;
cocos2d::Director::getInstance()->runWithScene(scene);
cocos2d::Application::getInstance()->run();
}
}
Is it possible to detect which CCScene is currently showing on the scene? I have 2 CCScenes in my game and I want a certain action to occur if one is showing.
Also quick related question, if I wanted to check if a CCMenu is not showing currently would I do something like
if (!menu) {
//Menu is not showing currently
}
I am a bit of a noob when it comes to Cocos2D so please forgive me :)
Thanks!
You can use the CCDirector to tell which scene is running.
[[CCDirector sharedDirector] runningScene];
As for whether the menu is showing. You would have to check with the parent of the menu. If the parent where your CCLayer, then you could check by
// assume menu is set up to have tag kMenuTag
CCMenu * menu = [self getChildByTag:kMenuTag];
If the menu is child of some other node, you can get the parent through a similar method and get a reference to the menu.
If the menu == nil, it is not showing.
UPDATE
In cocos2d, you are discouraged from keeping references to all of your sprites, instead you should be giving each node a unique tag and use that to reference it. To achieve your first goal, you can give your scene a tag in your 2 respective CCLayer classes.
You can set up your unique tags in an enum in a file called Tags.h, then import that into any classes that need access to your tags
Example Tags.h
enum {
kScene1Tag = 0,
kScene2Tag = 1,
kMenuTag = 2};
Then in your layer class
+(id) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
scene.tag = kScene1Tag;
// 'layer' is an autorelease object.
HelloWorld *layer = [HelloWorld node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
Now when you grab the current scene you can check against the tags
int currentSceneTag = [[CCDirector sharedDirector] runningScene].tag;
if (currentSceneTag == kScene1Tag) {
} else if (currentSceneTag == kScene2Tag) {
}
The tag property is from CCNode which is the base class of CCLayer, CCScene, CCSprite, CCMenu...
This how to find out which scene is running
if ([CCDirector sharedDirector].runningScene == yourScene1) {
// your scene 1 is showing
} else {
// your scene 2 is showing
}
and to find out if a node is child of the running scene
BOOL isShowing = NO;
CCNode *node = yourMenu;
while (node != nil) {
if (node == [CCDirector sharedDirector].runningScene) {
isShowing = YES;
break;
} else {
node = node.parent;
}
}
if (isShowing) {
// your menu is in the display hierarchy
}