Cannot stop label from accepting my touches - ios

I am working on a game where, when the user uses a skill, there is a time limit before he can use it again. Say 5 seconds, so I have a button, and in the middle of that button is a label which count downs the seconds till I am able to use said skill again.
During testing i noticed that my skill didnt, work since sometimes i would click the label node. Therefore i wrote
- (void)setupHUD
{
int barHeight = 50;
CGSize backgroundSize =
CGSizeMake(self.size.width, barHeight);
// myView.backgroundColor = [UIColor colorWithWhite:myWhiteFloat alpha:myAlphaFloat];
SKColor *backgroundColor =
[SKColor colorWithRed:0 green:1 blue:0.0 alpha:0.4];
SKSpriteNode *hudBarBackground =
[SKSpriteNode spriteNodeWithColor:backgroundColor
size:backgroundSize];
[hudBarBackground setUserInteractionEnabled:NO];
hudBarBackground.position =
CGPointMake(0, self.size.height - barHeight);
hudBarBackground.anchorPoint = CGPointZero;
[_hudLayer addChild:hudBarBackground];
timeButtTimmer = [SKLabelNode labelNodeWithFontNamed:#"Copperplate"];
tbutttimmer.userInteractionEnabled=NO;
// [tbutttimmer setUserInteractionEnabled: FALSE];
timeButtTimmer.name=#"label";
timeButtTimmer.fontSize=15;;
timeButtTimmer.position =
CGPointMake(self.size.width-75,
self.size.height - 30);
[_hudLayer addChild:timeButtTimmer];
}
Much to my surprise the label is still clickable and my nslog confirms that i can click it, since i have an nslog of the name of the node i touched.
I have modified my code to read
if ([node.name isEqualToString:#"button"] | [node.name isEqualToString:#"Readypras"])
I know this is dirty, but anyone has come across this before or am i doing something wrong. am i using the wrong property? thou in the documentation userInteraction is what sets if a node receives touch events.
-(id)initWithSize:(CGSize)size level:(int)level {
if (self = [super initWithSize:size]) {
_hudLayer = [SKNode node];
[_hudLayer setUserInteractionEnabled:NO];
[self addChild:_hudLayer];
[self setupHUD];
}
return self;
}
- (void)createUserInterface
{
SKLabelNode* startMsg =
[SKLabelNode labelNodeWithFontNamed:#"Chalkduster"];
startMsg.name = #"msgLabel";
startMsg.userInteractionEnabled=NO;
startMsg.text = #"Tap Screen to run!";
startMsg.fontSize = 32;
startMsg.position = CGPointMake(250, 150);
[self addChild: startMsg];
}

Related

Issues adding SKSpriteNode in SKScene initWithSize method in landscape orientation

When trying to add a SKSpriteNode at position 0,0 in my scenes initWithSize method, it is offset on the x axis. This is due to the positions still holding values for "portrait" orientation.
I've followed the advice in the following article by adding my scene in the "viewWillLayoutSubviews" method of the view controller, but I'm still experiencing an offset issue.
Here is the initWithSize method:
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.userInteractionEnabled = YES;
self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
self.physicsWorld.gravity = CGVectorMake(0.0f, -1.0f);
self.physicsWorld.contactDelegate = self;
SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:CGSizeMake(size.width,20)];
n1.position = CGPointMake(0, 0);
n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:n1.size];
n1.physicsBody.contactTestBitMask = catCategory;
n1.physicsBody.dynamic = NO;
n1.physicsBody.categoryBitMask = floorCategory;
[self addChild:n1];
}
return self;
}
Following Ray Wanderlich's article I was able to achieve success by using an offset, and applying it to the position when adding the sprite, but there HAS to be a better way, right?
-(id)initWithSize:(CGSize)size {
float center = 240.0;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && IS_WIDESCREEN) {
center = 284.0;
}
if (self = [super initWithSize:size]) {
self.userInteractionEnabled = YES;
self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
self.physicsWorld.gravity = CGVectorMake(0.0f, -1.0f);
self.physicsWorld.contactDelegate = self;
SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:CGSizeMake(size.width,20)];
n1.position = CGPointMake(center, 0);
n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:n1.size];
n1.physicsBody.contactTestBitMask = catCategory;
n1.physicsBody.dynamic = NO;
n1.physicsBody.categoryBitMask = floorCategory;
[self addChild:n1];
}
return self;
}
I'd like to find a comprehensive solution that doesn't rely on a hard-coded offset, and will work with landscape orientation regardless of if its an iPad or iPhone.
Thanks.

Moving a camera in SpriteKit

//UPDATE
The updated code has been added that works as I expected. See didSimulatePhysics method in the updated code below. In my case, I only care about moving a character left or right on the x axis where 0 on the x axis is the absolute left and right on the x axis is a configurable value. The Apple adventure game really helped a lot too.
//ORIGINAL POST BELOW
I'm working with Apple SpriteKit and I'm struggling to implement a camera as I would like it to behave. What I've done in the code is load a sprite character, two buttons, and a red box that is off to the right outside of the view at the start. What I'd like to be able to do is move the character with the buttons, and once the player reaches the middle or end of the screen, the camera will then re-adjust to uncover what couldn't be seen in the view. So moving to the right should eventually show the red box that is off outside of the view initially once the player gets there. However, with the code I'm using below, I'm unable to get the camera to follow and adjust the coordinates to the main character at all. I've looked at Apple's advanced scene processing doc as well as a few other stack overflow posts but can't seem to get it right. If anyone could offer some advice it would be appreciated.
#define cameraEdge 150
-(id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
/* Setup your scene here */
//320 568
self.backgroundColor = [SKColor whiteColor];
myWorld = [[SKNode alloc] init];
[self addChild:myWorld];
mainCharacter = [SKSpriteNode spriteNodeWithImageNamed:#"0"];
mainCharacter.physicsBody.dynamic = YES;
mainCharacter.name = #"player";
mainCharacter.position = CGPointMake(20, 20);
CGRect totalScreenSize = CGRectMake(0, 0, 800, 320);
SKSpriteNode *box = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(60, 60)];
SKSpriteNode *boxTwo = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(60, 60)];
SKSpriteNode *boxThree = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(60, 60)];
boxThree.position = CGPointMake(40, 50);
[myWorld addChild:boxThree];
boxTwo.position = CGPointMake(1100, 50);
box.position = CGPointMake(650, 50);
[myWorld addChild:box];
[myWorld addChild:boxTwo];
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:totalScreenSize];
self.physicsWorld.gravity = CGVectorMake(0, -5);
mainCharacter.name = #"mainCharacter";
mainCharacter.physicsBody.linearDamping = 0;
mainCharacter.physicsBody.friction = 0;
mainCharacter.physicsBody.restitution = 0;
mainCharacter.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:mainCharacter.size];
[myWorld addChild:mainCharacter];
[self addChild:[self buildLeftButton]];
[self addChild:[self buildRightButton]];
}
return self;
}
- (void)didSimulatePhysics
{
SKSpriteNode *hero = mainCharacter;
if(hero)
{
CGPoint heroPosition = hero.position;
CGPoint worldPosition = myWorld.position;
NSLog(#"%f", heroPosition.x);
CGFloat xCoordinate = worldPosition.x + heroPosition.x;
if(xCoordinate < cameraEdge && heroPosition.x > 0)
{
worldPosition.x = worldPosition.x - xCoordinate + cameraEdge;
self.worldMovedForUpdate = YES;
}
else if(xCoordinate > (self.frame.size.width - cameraEdge) && heroPosition.x < 2000)
{
worldPosition.x = worldPosition.x + (self.frame.size.width - xCoordinate) - cameraEdge;
self.worldMovedForUpdate = YES;
}
myWorld.position = worldPosition;
}
}
-(SKSpriteNode *)buildLeftButton
{
SKSpriteNode *leftButton = [SKSpriteNode spriteNodeWithImageNamed:#"left"];
leftButton.position = CGPointMake(20, 20);
leftButton.name = #"leftButton";
leftButton.zPosition = 1.0;
return leftButton;
}
-(SKSpriteNode *)buildRightButton
{
SKSpriteNode *leftButton = [SKSpriteNode spriteNodeWithImageNamed:#"right"];
leftButton.position = CGPointMake(60, 20);
leftButton.name = #"rightButton";
leftButton.zPosition = 1.0;
return leftButton;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if([node.name isEqualToString:#"leftButton"])
{
[mainCharacter.physicsBody applyImpulse:CGVectorMake(-120, 0)];
}
else if([node.name isEqualToString:#"rightButton"])
{
[mainCharacter.physicsBody applyImpulse:CGVectorMake(120, 10)];
}
}
If you want the view to always be centered on your player's position, modify your code with these points in mind:
1) Create a SKNode and call it myWorld, worldNode or any other name like that.
2) Add the worldNode [self addChild:worldNode];
3) Add all other nodes to the worldNode, including your player.
4) In the didSimulatePhysics method, add this code:
worldNode.position = CGPointMake(-(player.position.x-(self.size.width/2)), -(player.position.y-(self.size.height/2)));
Your view will now always be centered on your player's position.
Update May 2015:
If you are using a map created with Tiled Map Editor, you can use the free SKAToolKit framework. Features include player camera auto follow, test player, test HUD and sprite buttons.

How to make something like this?

I'm not sure if I'm correct in wording it "modal sprite-kit scene" but what I'm trying to do is have a smaller sized scene appear over a scene when the game is complete. Attached is a screenshot to show what I mean:
The screenshot is from Flappy Bird where when the player dies, the small game-over scene pops up almost like a modal effect, and displays the user's final results. I was wondering how to go about creating this.
I tried calling this when the game was done:
[self.player runAction:death completion:^{
[self removeAllActions];
GameOverNode *gameOverNode = [[GameOverNode alloc] initWithScore:self.size];
gameOverNode.gameScene = self;
gameOverNode.position = CGPointMake(self.scene.size.width/2, -150);
[self addChild:gameOverNode];
[gameOverNode runAction:[SKAction moveToY:self.scene.size.height/2 duration:0.6]];
And this was the code for the gameOverNode in the gameOverScene.m's file:
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.userInteractionEnabled = YES;
self.zPosition = 20;
SKSpriteNode *bg = [SKSpriteNode spriteNodeWithColor:[UIColor blackColor] size:CGSizeMake(280*DoubleIfIpad, 300*DoubleIfIpad)];
bg.alpha = 0.55;
But the node only shows up in the bottom left hand corner of the screen, as opposed to in the middle like I want it too.
What am I doing wrong? How can I make the small gameover node pop up and sit in the middle of the scene.
You simply can't. According to Apple Docs and multiple StackOverflow posts you cannot be running two SKScene's at the same time. To recreate the effect you want, you can create an SKShapeNode with border and line color similar to those you want, and place objects like score inside, or you can create an image for the screen that pops up and just add SKLabelNodes to the scene that show the high score and current score. I'm attaching a picture of how I created an end "view" for my app, Average Guy.
I made the popup screen using an SKShapeNode like this:
SKShapeNode *optionsMenu = [SKShapeNode node];
CGRect tempRect = CGRectMake(SELF_WIDTH/2, SELF_HEIGHT/2, SELF_WIDTH-20, (finalScoreLabel.position.y+(finalScoreLabel.frame.size.height/2)) - (mainMenuButton.position.y-(mainMenuButton.frame.size.height/2)) + 20);
CGPathRef tempPath = CGPathCreateWithRoundedRect(CGRectMake(tempRect.origin.x - tempRect.size.width/2, tempRect.origin.y - tempRect.size.height/2, tempRect.size.width, tempRect.size.height), 5, 5, Nil);
optionsMenu.path = tempPath;
optionsMenu.fillColor = [SKColor grayColor];
optionsMenu.strokeColor = [SKColor blueColor];
optionsMenu.zPosition = 30;
optionsMenu.glowWidth = 2.0f;
CGPathRelease(tempPath);
Of course, don't mind the hectic CGRect implementation, I wanted to make everything relative to fit all of the screen sizes so I didn't hardcode any of the positions. As for adding the score and the buttons, I did this:
SKLabelNode *restartButton = [SKLabelNode labelNodeWithFontNamed:#"00 Starmap Truetype"];
restartButton.text = #"Play Again";
restartButton.zPosition = 31;
restartButton.fontColor = [SKColor blueColor];
restartButton.fontSize = 30;
restartButton.position = CGPointMake(HALF_WIDTH, HALF_HEIGHT-50);
restartButton.name = #"restart_button";
SKLabelNode *restartButtonShadow = restartButton.copy;
restartButtonShadow.position = CGPointMake(restartButton.position.x+1, restartButton.position.y-1);
restartButtonShadow.color = [SKColor colorWithRed:0 green:0 blue:.5 alpha:.1];
SKLabelNode *mainMenuButton = [SKLabelNode labelNodeWithFontNamed:#"00 Starmap Truetype"];
mainMenuButton.text = #"Main Menu";
mainMenuButton.zPosition = 31;
mainMenuButton.fontColor = [SKColor blueColor];
mainMenuButton.fontSize = 30;
mainMenuButton.position = CGPointMake(HALF_WIDTH, HALF_HEIGHT - 85);
mainMenuButton.name = #"main_menu_button";

Deallocate SKScene after transition to another SKScene in SpriteKit

I have a view controller that has three skscenes as children.
When I transition from one to another, the old skscene doesn't get deallocated.
I want it to get deallocated as if it was never there.
Example:
When I first load the app, only 1 skscene is visible (say it takes up 100mb memory), then I transition to another (100mb more), and then the third (300mb memory).
I would end up with 300mb memory and I want to have 100 at all times.
How can I achieve this?
My view controller:
//
// ViewController.m
// Paddle Jumper
//
// Created by Chance Daniel on 1/18/14.
// Copyright (c) 2014 Max Hudson. All rights reserved.
//
#import "Flurry.h"
#import "ViewController.h"
#import "startViewController.h"
#implementation ViewController{
BOOL sceneSetUp;
}
- (void)viewWillLayoutSubviews
{
if(!sceneSetUp){
[super viewWillLayoutSubviews];
// Configure the view.
SKView * skView = (SKView *)self.view;
//skView.showsFPS = YES;
//skView.showsNodeCount = YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([[defaults objectForKey:#"firstTime"] intValue] != 1){
[defaults setObject:[NSNumber numberWithInt:1] forKey:#"firstTime"];
[defaults setObject:#"ggr" forKey:#"skinSelected"];
[defaults setObject:[NSNumber numberWithInt:2] forKey:#"ggrOwned"];
[defaults setObject:[NSNumber numberWithInt:5000] forKey:#"gona"];
[defaults setObject:[NSNumber numberWithInt:1500] forKey:#"points"];
[defaults setObject:[NSNumber numberWithInt:7] forKey:#"livesLeftValue"];
[defaults setObject:[NSNumber numberWithInt:3] forKey:#"shieldsLeftValue"];
[defaults setObject:[NSNumber numberWithInt:2] forKey:#"lvlTwoLeftValue"];
[defaults setObject:[NSNumber numberWithInt:0] forKey:#"lvlThreeLeftValue"];
}
if(![defaults objectForKey:#"tut_game1"]){
[defaults setObject:[NSNumber numberWithInt:1] forKey:#"tut_game1"];
[defaults setObject:[NSNumber numberWithInt:1] forKey:#"tut_store"];
[defaults setObject:[NSNumber numberWithInt:1] forKey:#"tut_daily"];
}
[defaults synchronize];
// Create and configure the scene.
SKScene * startScene = [StartViewController sceneWithSize:skView.bounds.size];
startScene.scaleMode = SKSceneScaleModeAspectFill;
// Present the scene.
[skView presentScene:startScene];
//[skView presentScene:scene];
sceneSetUp = YES;
}
}
-(void) switchScene{
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return UIInterfaceOrientationMaskAllButUpsideDown;
} else {
return UIInterfaceOrientationMaskAll;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
An SKScene that won't release: //
// SettingsSKScene.m
// Paddle Jumper
//
// Created by Max Hudson on 3/15/14.
// Copyright (c) 2014 Max Hudson. All rights reserved.
//
#import "SettingsSKScene.h"
#import "gameViewController.h"
#import "StoreScene.h"
#interface SettingsSKScene (){
SKSpriteNode *bg;
SKSpriteNode *masterOverlay;
SKSpriteNode *wbox;
SKSpriteNode *gamecenter;
SKSpriteNode *max;
SKSpriteNode *chance;
SKSpriteNode *bryce;
SKSpriteNode *home;
SKSpriteNode *play;
SKSpriteNode *chance_link;
SKSpriteNode *max_link;
SKSpriteNode *bryce_link;
SKSpriteNode *fbButton;
SKSpriteNode *fbToggleYes;
SKSpriteNode *fbToggleNo;
SKLabelNode *story1;
SKLabelNode *story2;
SKLabelNode *story3;
SKLabelNode *chance_name;
SKLabelNode *max_name;
SKLabelNode *bryce_name;
SKLabelNode *chance_role;
SKLabelNode *max_role;
SKLabelNode *bryce_role;
SKLabelNode *chance_handle;
SKLabelNode *max_handle;
SKLabelNode *bryce_handle;
SKTexture *bg_texture;
SKTexture *gamecenter_texture;
SKTexture *wbox_texture;
SKTexture *max_texture;
SKTexture *chance_texture;
SKTexture *bryce_texture;
SKTexture *home_texture;
SKTexture *play_texture;
SKTexture *fb_texture;
SKTexture *toggle_yes_texture;
SKTexture *toggle_no_texture;
}
#end
#implementation SettingsSKScene
-(id) initWithSize:(CGSize)size{
if(self = [super initWithSize:size]){
masterOverlay = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:self.frame.size];
masterOverlay.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
[self addChild:masterOverlay];
bg_texture = [SKTexture textureWithImageNamed:#"settings_bg"];
wbox_texture = [SKTexture textureWithImageNamed:#"white_rect_bg"];
gamecenter_texture = [SKTexture textureWithImageNamed:#"gc"];
max_texture = [SKTexture textureWithImageNamed:#"max"];
chance_texture = [SKTexture textureWithImageNamed:#"chance"];
bryce_texture = [SKTexture textureWithImageNamed:#"bryce"];
home_texture = [SKTexture textureWithImageNamed:#"home_light"];
play_texture = [SKTexture textureWithImageNamed:#"play_light"];
fb_texture = [SKTexture textureWithImageNamed:#"fb_light"];
toggle_yes_texture = [SKTexture textureWithImageNamed:#"toggle_yes"];
toggle_no_texture = [SKTexture textureWithImageNamed:#"toggle_no"];
NSArray *to_preload = #[bg_texture, wbox_texture, gamecenter_texture, max_texture, chance_texture, bryce_texture, home_texture, play_texture, fb_texture, toggle_yes_texture, toggle_no_texture];
[SKTexture preloadTextures:to_preload withCompletionHandler:^{
[self fadeRemove:masterOverlay];
[self initialize];
}];
}
return self;
}
-(void) fadeRemove: (SKNode *) node{
double duration = arc4random() % 10;
duration *= 0.05;
SKAction *fadeOut = [SKAction fadeOutWithDuration:0.1+duration];
SKAction *remove = [SKAction runBlock:^{
[node removeFromParent];
}];
[node runAction:[SKAction sequence:#[fadeOut, remove]]];
}
-(void) initialize{
bg = [SKSpriteNode spriteNodeWithTexture:bg_texture];
bg.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
bg.zPosition = 0;
wbox = [SKSpriteNode spriteNodeWithTexture:wbox_texture];
wbox.position = CGPointMake(self.frame.size.width/2, 70);
wbox.alpha = 0.8;
wbox.zPosition = 2;
gamecenter = [SKSpriteNode spriteNodeWithTexture:gamecenter_texture];
gamecenter.position = CGPointMake(self.frame.size.width/2 + 100, self.frame.size.height/2-2);
gamecenter.name = #"gc";
gamecenter.zPosition = 2;
fbButton = [SKSpriteNode spriteNodeWithTexture:fb_texture];
fbButton.size = CGSizeMake(36, 36);
fbButton.position = CGPointMake(self.frame.size.width/2 - 115, self.frame.size.height/2-2);
fbButton.name = #"fb";
fbButton.zPosition = 2;
fbToggleNo = [SKSpriteNode spriteNodeWithTexture:toggle_no_texture];
fbToggleNo.position = CGPointMake(self.frame.size.width/2 - 50, self.frame.size.height/2-2);
fbToggleNo.size = CGSizeMake(fbToggleNo.size.width/3, fbToggleNo.size.height/3);
fbToggleNo.name = #"fbno";
fbToggleNo.zPosition = 2;
fbToggleYes = [SKSpriteNode spriteNodeWithTexture:toggle_yes_texture];
fbToggleYes.position = CGPointMake(self.frame.size.width/2 - 70, self.frame.size.height/2-2);
fbToggleYes.name = #"fbyes";
fbToggleYes.zPosition = 2;
int hpBuffer = 40;
int hpZ = 2;
home = [SKSpriteNode spriteNodeWithTexture:home_texture];
home.position = CGPointMake(hpBuffer, self.frame.size.height - hpBuffer);
home.zPosition = hpZ;
home.name = #"home";
play = [SKSpriteNode spriteNodeWithTexture:play_texture];
play.position = CGPointMake(self.frame.size.width - hpBuffer, self.frame.size.height - hpBuffer);
play.zPosition = hpZ;
play.name = #"play";
[self addChild:bg];
[self addChild:wbox];
[self addChild:gamecenter];
[self addChild:home];
[self addChild:play];
[self addChild:fbButton];
[self addChild:fbToggleNo];
[self addCredits];
[self addStory];
}
-(void) addCredits{
/* images */
int cmbZ = wbox.zPosition + 1;
int cmbY = wbox.position.y;
int cmbXUnit = 132;
int cmbX = self.frame.size.width/2 - (3*cmbXUnit)/2 + 20;
int cmbWidth = 40;
chance = [SKSpriteNode spriteNodeWithTexture:chance_texture];
max = [SKSpriteNode spriteNodeWithTexture:max_texture];
bryce = [SKSpriteNode spriteNodeWithTexture:bryce_texture];
chance.zPosition = cmbZ;
max.zPosition = cmbZ;
bryce.zPosition = cmbZ;
chance.position = CGPointMake(cmbX+cmbXUnit*0, cmbY+3);
max.position = CGPointMake(cmbX+cmbXUnit*1 + 10, cmbY);
bryce.position = CGPointMake(cmbX+cmbXUnit*2 + 10, cmbY+5);
chance.size = CGSizeMake(cmbWidth, (chance.size.height/chance.size.width)*cmbWidth);
max.size = CGSizeMake(cmbWidth, (max.size.height/max.size.width)*cmbWidth);
bryce.size = CGSizeMake(cmbWidth, (bryce.size.height/bryce.size.width)*cmbWidth);
[self addChild:chance];
[self addChild:max];
[self addChild:bryce];
/* names */
int cmb_nameXUnit = 30;
int cmb_nameY = wbox.position.y - 10;
int cmb_nameFontSize = 18;
chance_name = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
max_name = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
bryce_name = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
chance_name.text = #"Chance Daniel";
max_name.text = #"Max Hudson";
bryce_name.text = #"Bryce Daniel";
chance_name.fontColor = [SKColor blackColor];
max_name.fontColor = [SKColor blackColor];
bryce_name.fontColor = [SKColor blackColor];
chance_name.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
max_name.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
bryce_name.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
chance_name.position = CGPointMake(chance.position.x + cmb_nameXUnit, cmb_nameY);
max_name.position = CGPointMake(max.position.x + cmb_nameXUnit, cmb_nameY);
bryce_name.position = CGPointMake(bryce.position.x + cmb_nameXUnit, cmb_nameY);
chance_name.fontSize = cmb_nameFontSize;
max_name.fontSize = cmb_nameFontSize;
bryce_name.fontSize = cmb_nameFontSize;
chance_name.zPosition = cmbZ;
max_name.zPosition = cmbZ;
bryce_name.zPosition = cmbZ;
[self addChild:chance_name];
[self addChild:max_name];
[self addChild:bryce_name];
/* roles */
int cmb_roleY = wbox.position.y - 25;
int cmb_roleFontSize = 11;
chance_role = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
max_role = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
bryce_role = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
chance_role.text = #"Programmer";
max_role.text = #"Programmer";
bryce_role.text = #"Graphic Designer";
chance_role.fontColor = [SKColor darkGrayColor];
max_role.fontColor = [SKColor darkGrayColor];
bryce_role.fontColor = [SKColor darkGrayColor];
chance_role.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
max_role.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
bryce_role.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
chance_role.position = CGPointMake(chance.position.x + cmb_nameXUnit + 19, cmb_roleY);
max_role.position = CGPointMake(max.position.x + cmb_nameXUnit + 12, cmb_roleY);
bryce_role.position = CGPointMake(bryce.position.x + cmb_nameXUnit + 6, cmb_roleY);
chance_role.fontSize = cmb_roleFontSize;
max_role.fontSize = cmb_roleFontSize;
bryce_role.fontSize = cmb_roleFontSize;
chance_role.zPosition = cmbZ;
max_role.zPosition = cmbZ;
bryce_role.zPosition = cmbZ;
[self addChild:chance_role];
[self addChild:max_role];
[self addChild:bryce_role];
/* twitter handles */
int cmb_handY = wbox.position.y - 40;
int cmb_handFontSize = 10;
chance_handle = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
max_handle = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
bryce_handle = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
chance_handle.text = #"#ChanceOfThat";
max_handle.text = #"#max_hud";
bryce_handle.text = #"#BryceOfLife";
chance_handle.fontColor = [SKColor darkGrayColor];
max_handle.fontColor = [SKColor darkGrayColor];
bryce_handle.fontColor = [SKColor darkGrayColor];
chance_handle.position = CGPointMake(chance.position.x, cmb_handY);
max_handle.position = CGPointMake(max.position.x, cmb_handY);
bryce_handle.position = CGPointMake(bryce.position.x, cmb_handY);
chance_handle.fontSize = cmb_handFontSize;
max_handle.fontSize = cmb_handFontSize;
bryce_handle.fontSize = cmb_handFontSize;
chance_handle.zPosition = cmbZ;
max_handle.zPosition = cmbZ;
bryce_handle.zPosition = cmbZ;
[self addChild:chance_handle];
[self addChild:max_handle];
[self addChild:bryce_handle];
/* touchzones */
CGSize cmdL_size = CGSizeMake(120, 70);
SKColor *cmdL_color = [SKColor clearColor];
int cmdLZ = 3;
int cmdLX = cmbX + 40;
chance_link = [SKSpriteNode spriteNodeWithColor:cmdL_color size:cmdL_size];
max_link = [SKSpriteNode spriteNodeWithColor:cmdL_color size:cmdL_size];
bryce_link = [SKSpriteNode spriteNodeWithColor:cmdL_color size:cmdL_size];
chance_link.position = CGPointMake(cmdLX+cmbXUnit*0, cmbY);
max_link.position = CGPointMake(cmdLX+cmbXUnit*1 + 10, cmbY);
bryce_link.position = CGPointMake(cmdLX+cmbXUnit*2 + 10, cmbY);
chance_link.zPosition = cmdLZ;
max_link.zPosition = cmdLZ;
bryce_link.zPosition = cmdLZ;
chance_link.name = #"c_handle";
max_link.name = #"m_handle";
bryce_link.name = #"b_handle";
[self addChild:chance_link];
[self addChild:max_link];
[self addChild:bryce_link];
}
-(void) addStory{
int stX = self.frame.size.width/2;
int stZ = 2;
SKColor *stColor = [SKColor whiteColor];
story1 = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
story2 = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
story3 = [SKLabelNode labelNodeWithFontNamed:#"BebasNeue"];
story1.text = #"Gon";
story2.text = #"Help Gon-Gon and his friends get";
story3.text = #"Back to the time they came from!";
story1.fontColor = stColor;
story2.fontColor = stColor;
story3.fontColor = stColor;
story1.zPosition = stZ;
story2.zPosition = stZ;
story3.zPosition = stZ;
story1.position = CGPointMake(stX, self.frame.size.height - 55);
story1.fontSize = 50;
story2.position = CGPointMake(stX, self.frame.size.height - 95);
story2.fontSize = 30;
story3.position = CGPointMake(stX, self.frame.size.height - 120);
story3.fontSize = 20;
[self addChild:story1];
[self addChild:story2];
[self addChild:story3];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touchUI = [touches anyObject];
CGPoint touchPoint = [touchUI locationInNode:self];
SKNode *touchNode = [self nodeAtPoint:touchPoint];
if([touchNode.name isEqualToString:#"home"]){
StartViewController *svc = [[StartViewController alloc] initWithSize:self.size];
SKTransition *fade = [SKTransition fadeWithColor :[SKColor blackColor] duration:0.4];
[self.view presentScene:svc transition:fade];
}
if([touchNode.name isEqualToString:#"play"]){
gameViewController *gvc = [[gameViewController alloc] initWithSize:self.size];
SKTransition *fade = [SKTransition fadeWithColor :[SKColor blackColor] duration:0.4];
[self.view presentScene:gvc transition:fade];
}
if([touchNode.name isEqualToString:#"gc"]){
NSDictionary * dict = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithBool:1], #"showGC", nil];
[[NSNotificationCenter defaultCenter]postNotificationName:#"kNotificationUpdateBannerView" object:self userInfo:dict];
}
if([touchNode.name isEqualToString:#"c_handle"]){
NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:#"%#", #"twitter:///user?screen_name=ChanceOfThat"]];
int worked = [[UIApplication sharedApplication] openURL:urlApp];
if(!worked){
NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:#"%#", #"https://twitter.com/#!/ChanceOfThat"]];
[[UIApplication sharedApplication] openURL:urlApp];
}
}
if([touchNode.name isEqualToString:#"m_handle"]){
NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:#"%#", #"twitter:///user?screen_name=max_hud"]];
int worked = [[UIApplication sharedApplication] openURL:urlApp];
if(!worked){
NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:#"%#", #"https://twitter.com/#!/max_hud"]];
[[UIApplication sharedApplication] openURL:urlApp];
}
}
if([touchNode.name isEqualToString:#"b_handle"]){
NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:#"%#", #"twitter:///user?screen_name=BryceOfLife"]];
int worked = [[UIApplication sharedApplication] openURL:urlApp];
if(!worked){
NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:#"%#", #"https://twitter.com/#!/BryceOfLife"]];
[[UIApplication sharedApplication] openURL:urlApp];
}
}
}
#end
A similar problem was faced by the person who asked this question.
When asked whether he was able to solve it, they said:
Yes, I did, there wasn't anything I could do about it from the scene
or Sprite Kit for that matter, I simply needed to remove the scene and
the view containing it completely from the parent view, cut all its
bonds to the other parts of the system, in order for the memory to be
deallocated as well.
You should use separate views for each of your scene and transition between these views. You can follow these steps to make it look natural:
1 - At the point you want to transition from one scene to the other, take a snapshot of the scene using the following code:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Then, add this image as a subview of the SKView of the current scene, and remove the scene.
2 - Initialise the new scene on another view, and transition between the two views using UIView animation.
3 - Remove the first view from it's superview.
I am just starting out with SpriteKit in Swift and I had the same problem: My intro scene was playing some music that I wanted to stop after transitioning to the main menu scene, and I figured the deinit would be a good place to put the AVAudioPlayer.stop() call in, but deinit was never being called.
After looking around I learned that it may be because of some strong references to the scene, so in my GameViewController:UIViewController subclass I changed this code:
let intro = IntroScene(size: skView.bounds.size)
skView.presentScene(intro)
to
skView.presentScene(IntroScene(size: skView.bounds.size))
and in the intro scene, that I wanted to be deallocated, I changed
let mainMenu = MainMenuScene(size: self.size)
let crossFade = SKTransition.crossFadeWithDuration(1)
self.scene.view.presentScene(mainMenu, transition: crossFade)
to
self.scene.view.presentScene(MainMenuScene(size: self.size),
transition: SKTransition.crossFadeWithDuration(1))
and it worked! After the transition was complete the deinit method got called.
I assume that the outgoing scene was not being deinitialized because there were variables holding references to it.
December 2019/Swift 5
Update:
My layout:
I have a single view controller that contains 2 SKViews which each of them have their own unique SKScene that are presented at the same time. One SKView & its SKScene is the main overworld where the player character is rendered, controlled, NPC's rendered, camera tracking, the whole shebang etc., & the other SKView & its SKScene display the mini map of the overworld.
You can imagine there are also quite a number of SKSpriteNode's & lot of them ALWAYS have some kind of SKAction/animation running non-stop (swaying trees for instance). My SKScenes even contain their own arrays pointing at specific groups of SKSpriteNodes, such as, character nodes, building nodes, tree nodes. This is for quick access & convenience purposes.
Plus, I have a few singletons that either contain an array of SKTextures, or character models, etc.. They are kept around as an optimization for quick data access rather than reading from disc/accessing storage every time I need something.
There are even UIKit elements used for the game UI inside the view controller.
Many other objects, such as, my models that contain data on characters, buildings, the entire game session all have some kind of delegates pointing at someone. On top of all of this the codebase is massive.
After observing memory in the debug session I found out the sure-fire way to make sure nothing is retained is to absolutely make sure the following:
Memory handling:
Pass in nil for scene presentation & set that skview's property/pointer to nil as well
Remove all view controller primary view subviews
Absolutely set every delegate you have to nil !!!!!!!!!!!!!!
Remove all observers IF you happen to have any
Anywhere you have an array/dictionary or pointer to some kind of object YOU created, set it to nil/empty it
CRITICAL: put all of the above into a single function/method & make sure to call it right before changing view controllers!
*NOTE: IF you have 1 view controller for the entire app (congrats on squeezing everything - youz overlord squeezer), then do NOT nil everything & use caution. BUT the previous scene still needs to be set to nil during presentation.
So something like this if you're jumping between view controllers:
/// Remove all pointers to any data, nodes & views.
fileprivate func cleanUp() {
guard self.skView != nil else { return }
// Session was passing data updates to this view controller; time to nil it
self.gameSessionModel.delegate = nil
self.skView.presentScene(nil)
self.skViewMiniMap.presentScene(nil)
self.skView = nil
self.skViewMiniMap = nil
for subview in self.view.subviews {
subview.removeFromSuperview()
}
}
/// Take the user back to the main menu module/view controller.
fileprivate func handleMenuButton() {
// First, clean up everything
self.cleanUp()
// Then go to the other view controller
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MainViewController")
self.show(view, sender: .none)
}
Call handleMenuButton() function or whatever function you use to present another view controller, but make sure the cleanUp() function is called within it!
*NOTE: Classes such as 'gameSessionModel' are entirely my own custom classes. Xcode will throw an error on such things (unless you magically have the same one...) so delete such things. They are only used as example code in case you have delegates pointing at the current view controller.
If you're only presenting different SKScene's with a single SKView, then your cleanUp() function can end up being "lighter" as such:
/// Remove all pointers to any data, nodes & views.
fileprivate func cleanUp() {
self.skView.presentScene(nil)
// Previous scene was set to nil, its deinit called. Now onto the new scene:
let gameScene = self.setupGameScene(id: "perhapsYouUseStringIDsToDisntiguishBetweenScenes?")
self.skView.presentScene(gameScene)
}
*NOTE: Do NOT forget to use the SKScene's deinit method to remove anything you won't need. It's a practice I use all the time for all my classes to untangle anything I might have missed.
There's nothing wrong with SKScene or SKView, as long as I can see. Make sure the scene instance is not strongly reference anywhere else, especially inside a block. Blocks are highly probable to be ignored.
More about weak reference inside a block: https://stackoverflow.com/a/17105368/571489
As far as I see, you do have a block strongly referencing the scene instance:
[SKTexture preloadTextures:to_preload withCompletionHandler:^{
[self fadeRemove:masterOverlay];
[self initialize];
}];
EDIT: My previous idea about an NSTimer was irrelevant
To make sure this is an issue isolated to this scene, override the dealloc methods of all scenes you might have (including this one) like this:
-(void)dealloc {
NSLog(#"Dealloc <scene name>");
}
Look at your other scene transitions, see if they deallocate properly. Find the differences between these scenes. This will help you see if it's an isolated issue or a bigger problem. Once you have the problem fixed be sure to comment out or remove the dealloc method as it is overriding the one that actually deallocates the memory. Hopefully this helps!

How to calibrate a sprites touchLocation after zoom

I add a sprite on the background sprite and then zoom (pinch) the background and by that the sprite as well.
After the zoom i want to be able to click right on the "zoomed" sprite and then move (pan) it. However, to catch the sprite i have to click outside of the sprite. I guess that is due to the zoom and coordinates.
I would really need some help how to make it so that i always only need to click on the actual sprite if it is in it's original state or zoomed up or down.
I will also implement UIScrollView so i can move around the background but would like to fix this first.
Here is the code i use to test this:
- (void)didMoveToView:(SKView *)view {
_background = [SKSpriteNode spriteNodeWithImageNamed:#"background"];
_background.name = #"background";
[_background setAnchorPoint:CGPointZero];
// _background.anchorPoint = CGPointMake(0.0, 0.1);
self.scaleMode = SKSceneScaleModeResizeFill;
[self addChild:_background];
SKLabelNode *texT = [SKLabelNode labelNodeWithFontNamed:#"Ariel"];
texT.text = #"X";
texT.position = CGPointMake(160, 260);
[_background addChild:texT];
_panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(handlePan:)];
[self.view addGestureRecognizer:_panGesture];
_pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(handlePinch:)];
[self.view addGestureRecognizer:_pinchGesture];
/* Setup your scene here */
self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:#"Spaceship"];
sprite.xScale = 0.2;
sprite.yScale = 0.2;
sprite.position = CGPointMake(160, 260);
sprite.name = #"sprite";
[_background addChild:sprite];
}
- (void)handlePan:(UIPanGestureRecognizer *)sender {
NSLog(#"handlePan:");
if (![_currentNode.name isEqualToString:#"background"]) {
_touchLocation = [sender locationInView:sender.view];
_touchLocation = [self convertPointFromView:_touchLocation];
_currentNode.position = _touchLocation;
}
}
- (void)handlePinch:(UIPinchGestureRecognizer *) sender {
NSLog(#"handlePinch: %f",sender.scale);
[self runAction:[SKAction scaleBy:sender.scale duration:0]];
sender.scale = 1;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"touchesBegan");
//////DO THE FIRST TOUCH//////
_actualTouch = [touches anyObject];
_touchLocation = [_actualTouch locationInNode:self];
_currentNode = [self nodeAtPoint:_touchLocation];
NSLog(#"TouchBegan:_touchLocation:%#", NSStringFromCGPoint(_touchLocation));
NSLog(#"_currentNode.name: %#", _currentNode.name);
}
#end
I had this same problem and I found that the solution is to resize instead of scale. The physics seem to still work as expected and now the touch events will too. I came across this solution here. The scaleMode in your didMoveToView needs to be changed as well, see below.
self.scaleMode = SKSceneScaleModeAspectFill;
- (void)handlePinch:(UIPinchGestureRecognizer *) sender {
NSLog(#"handlePinch: %f",sender.scale);
//[self runAction:[SKAction scaleBy:sender.scale duration:0]];
self.size = CGSizeMake(self.size.width/sender.scale,self.size.height/sender.scale);
sender.scale = 1;
}
In my own implementation I had set upper and lower limits to the zoom level as well.

Resources