SpriteKit: Having trouble updating text of a SKLabelNode during runtime (2 approaches) - sprite-kit

I want to set the text of a label based on a User's tapping on a Node. I've tried two approaches, neither of which have worked as intended.
Approach #1: Declare the SKLabelNode globally, update sklabelnode.text at runtime.
Code:
import SpriteKit
class GameScene: SKScene {
//Level 0
var q0Label:SKLabelNode!
var q1Label:SKLabelNode!
let gem = SKSpriteNode(imageNamed:"Destiny_Gem")
let energy = SKSpriteNode(imageNamed: "Destiny_Energy")
let money = SKSpriteNode(imageNamed: "Destiny_Money")
override func didMoveToView(view: SKView) {
//Level 0 - Choose your Destiny
//Add a label to the scene
q0Label = SKLabelNode(fontNamed: "Courier")
q0Label.text = "Why do you want to be a Doctor?"
q0Label.fontSize = 30
q0Label.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(q0Label)
q1Label = SKLabelNode(fontNamed: "Courier")
q1Label.fontSize = 25
q1Label.position = CGPoint(x:frame.size.width * 0.5, y: frame.size.height * 0.3)
//Position the sprites
gem.position = CGPoint(x:frame.size.width * 0.2, y: frame.size.height * 0.4)
gem.zPosition = 2
[gem.setScale(0.5)]
gem.name = "gem"
energy.position = CGPoint(x:frame.size.width * 0.5, y: frame.size.height * 0.4)
energy.zPosition = 2
[energy.setScale(0.5)]
energy.name = "energy"
money.position = CGPoint(x:frame.size.width * 0.8, y: frame.size.height * 0.4)
money.zPosition = 2
[money.setScale(0.25)]
money.name = "money"
//Add sprites to scene
addChild(gem)
addChild(energy)
addChild(money)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = (touch as! UITouch).locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "gem" {
q1Label.text = "Like my parents before me, it is my destiny."
self.addChild(q1Label)
}
else if theName == "energy" {
q1Label.text = "The people of the world need my help."
self.addChild(q1Label)
}
else if theName == "money" {
q1Label.text = "I want to be rich and famous."
self.addChild(q1Label)
}
}
}
}
}
Problem: This will work the first time you click a Node, however the very next click, the application will crash, with this error message:
"Attemped to add a SKNode which already has a parent error"
I then read various solutions on SO about not declaring the object globally. That lead to Approach #2.
Approach #2: Declare the label conditionally.
Code:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = (touch as! UITouch).locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "gem" {
var q1Label:SKLabelNode!
q1Label = SKLabelNode(fontNamed: "Courier")
q1Label.fontSize = 25
q1Label.position = CGPoint(x:frame.size.width * 0.5, y: frame.size.height * 0.3)
q1Label.text = "Like my parents before me, it is my destiny."
//set destiny variable = gem
self.addChild(q1Label)
}
else if theName == "energy" {
var q1Label:SKLabelNode!
q1Label = SKLabelNode(fontNamed: "Courier")
q1Label.fontSize = 25
q1Label.position = CGPoint(x:frame.size.width * 0.5, y: frame.size.height * 0.3)
q1Label.text = "The people of the world need my help."
//set destiny variable = energy
self.addChild(q1Label)
}
else if theName == "money" {
var q1Label:SKLabelNode!
q1Label = SKLabelNode(fontNamed: "Courier")
q1Label.fontSize = 25
q1Label.position = CGPoint(x:frame.size.width * 0.5, y: frame.size.height * 0.3)
q1Label.text = "I want to be rich and famous."
//set destiny variable = money
self.addChild(q1Label)
}
}
}
}
}
Problem: This just creates the labels over the top of each other; I don't know how to clean up any that were created earlier.

Re-creating labels in this case is really unnecessary. You only want to update a label based on which button is clicked. The only thing you need to do is to create those two labels once in didMoveToView method and update them accordingly, like this (just copy/past this code to try):
import SpriteKit
class GameScene: SKScene {
//Level 0
var q0Label:SKLabelNode!
var q1Label:SKLabelNode!
let gem = SKSpriteNode(imageNamed:"Destiny_Gem")
let energy = SKSpriteNode(imageNamed: "Destiny_Energy")
let money = SKSpriteNode(imageNamed: "Destiny_Money")
override func didMoveToView(view: SKView) {
//Level 0 - Choose your Destiny
//Add a label to the scene
q0Label = SKLabelNode(fontNamed: "Courier")
q0Label.text = "Why do you want to be a Doctor?"
q0Label.fontSize = 30
q0Label.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(q0Label)
q1Label = SKLabelNode(fontNamed: "Courier")
q1Label.fontSize = 25
q1Label.position = CGPoint(x:frame.size.width * 0.5, y: frame.size.height * 0.3)
q1Label.text = ""
self.addChild(q1Label)
//Position the sprites
gem.position = CGPoint(x:frame.size.width * 0.35, y: frame.size.height * 0.4)
gem.zPosition = 2
[gem.setScale(0.5)]
gem.name = "gem"
energy.position = CGPoint(x:frame.size.width * 0.3, y: frame.size.height * 0.4)
energy.zPosition = 2
[energy.setScale(0.5)]
energy.name = "energy"
money.position = CGPoint(x:frame.size.width * 0.4, y: frame.size.height * 0.4)
money.zPosition = 2
[money.setScale(0.25)]
money.name = "money"
//Add sprites to scene
addChild(gem)
addChild(energy)
addChild(money)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = (touch as UITouch).locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "gem" {
q1Label.text = "Like my parents before me, it is my destiny."
}
else if theName == "energy" {
q1Label.text = "The people of the world need my help."
}
else if theName == "money" {
q1Label.text = "I want to be rich and famous."
}
}
}
}
}
Just don't re-add those labels multiple times. And about the error you are getting...Keep in mind that node can have only one parent at the time, and that's why you are getting the error which saying that certain label already has a parent.

Related

In swift for spritekit, how would I change the textures of nodes when they are placed?

I’m currently working on a matching game and when the user touches the nodes (Fruit match cards) I want them to display different images when a user clicks the nodes (Fruit match cards).
This is my current code:
import Foundation
import SpriteKit
class EasyScreen: SKScene {
override func didMove(to view: SKView) {
var background = SKSpriteNode(imageNamed: "Easy Screen Background")
let timerText = SKLabelNode(fontNamed: "Arial")
timerText.fontSize = 40
timerText.fontColor = SKColor.white
timerText.position = CGPoint(x: 20, y: 400)
timerText.zPosition = 1
var counter:Int = 120
timerText.run(
SKAction.repeatForever(
SKAction.sequence(
[
SKAction.run {
counter -= 1
timerText.text = " Time: \(counter)"
print("\(counter)")
if counter <= 0 {
let newScene = TryAgainScreen(fileNamed: "Try Again Screen")
newScene?.scaleMode = .aspectFill
self.view?.presentScene(newScene)
}
},
SKAction.wait(forDuration: 1)
]
)
)
)
background.position = CGPoint(x: 0, y: 0)
background.size.width = self.size.width
background.size.height = self.size.height
background.anchorPoint = CGPoint(x: 0.5,y: 0.5)
let matchCardOne = SKSpriteNode(imageNamed: "Fruit Match Card")
let matchCardTwo = SKSpriteNode(imageNamed: "Fruit Match Card")
let matchCardThree = SKSpriteNode(imageNamed: "Fruit Match Card")
let matchCardFour = SKSpriteNode(imageNamed: "Fruit Match Card")
matchCardOne.name = "FruitMatchCard1"
matchCardTwo.name = "FruitMatchCard2"
matchCardThree.name = "FruitMatchCard3"
matchCardFour.name = "FruitMatchCard4"
matchCardOne.size = CGSize(width: 150, height: 300)
matchCardTwo.size = CGSize(width: 150, height: 300)
matchCardThree.size = CGSize(width: 150, height: 300)
matchCardFour.size = CGSize(width: 150, height: 300)
matchCardOne.zPosition = 1
matchCardTwo.zPosition = 1
matchCardThree.zPosition = 1
matchCardFour.zPosition = 1
matchCardOne.anchorPoint = CGPoint(x: 0.5, y: 0.5)
matchCardTwo.anchorPoint = CGPoint(x: 0.5, y: 0.5)
matchCardThree.anchorPoint = CGPoint(x: 0.5, y: 0.5)
matchCardFour.anchorPoint = CGPoint(x: 0.5, y: 0.5)
matchCardOne.position = CGPoint(x: -125, y: 60)
matchCardTwo.position = CGPoint(x: -125, y: -260)
matchCardThree.position = CGPoint(x: 70, y: 60)
matchCardFour.position = CGPoint(x: 70 , y: -260)
addChild(background)
addChild(matchCardOne)
addChild(matchCardTwo)
addChild(matchCardThree)
addChild(matchCardFour)
addChild(timerText)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view?.isMultipleTouchEnabled = false
let touch = touches.first
let positionInScene = touch!.location(in: self)
let touchedCardOneNode = self.atPoint(positionInScene)
if let name = touchedCardOneNode.name {
if name == "FruitMatchCard1" {
let newTexture = SKTexture(imageNamed: "Apple")
FruitMatchCard1.init(texture: newTexture)
}
}
let touchTwo = touches.first
let positionInSceneTwo = touch!.location(in: self)
let touchedCardTwoNode = self.atPoint(positionInScene)
if let name = touchedCardTwoNode.name {
if name == "FruitMatchCard2" {
FruitMatchCard2.init(imageNamed: "Banana")
}
}
let touchThree = touches.first
let positionInSceneThree = touch!.location(in: self)
let touchedCardThreeNode = self.atPoint(positionInScene)
if let name = touchedCardThreeNode.name {
if name == "FruitMatchCard3" {
FruitMatchCard3.init(imageNamed: "Apple")
}
}
let touchFour = touches.first
let positionInSceneFour = touch!.location(in: self)
let touchedCardFourNode = self.atPoint(positionInScene)
if let name = touchedCardFourNode.name {
if name == "FruitMatchCard4" {
FruitMatchCard4.init(imageNamed: "Banana")
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
I’m trying to change the textures of the nodes in this part of the code. Inside the “if name == “FruitMatchCard” { } “ part of the code. However, when I launch the Xcode simulator the node’s textures aren't changing.
Any advice on how I can do this? Thanks!
Your fundamental problem is that when someone taps a card, you are creating a new card with the new texture and not doing anything with it. Take the following code you have:
FruitMatchCard2.init(imageNamed: "Banana")
This code creates a match card, but you don't do anything with the card.
To change the texture of the card, you must get the sprite node of the tapped card and change its texture. I see in your code you have the following variable:
let touchedCardTwoNode = self.atPoint(positionInScene)
This variable has the card that was touched. Set its texture to the texture you want to use.
touchedCardTwoNode.texture = SKTexture(imageNamed: "Banana")
My SpriteKit is a bit rusty so I can't guarantee that example will compile, but it gives you an idea of what you need to do to change the texture when tapping a card.

SKAction not running when button is held

I am working/practicing with SpriteKit and making a directional pad for controls. It works to move the character, except for the SKAction. I have the actions in the Actions.sks file that based off what button is pressed determines the action that is called. When I press the button the character moves fine, but when I hold it the character glides and the walking animation is stuck on the first frame until I release. What I am trying to do is have the character move if the button is pressed, and continue moving(with walking animation) when the button is held. I am trying to make it look like the gameboy era games.
class GameScene: SKScene {
var player = SKSpriteNode()
var playerSpeed: CGFloat = 0
var previousTimeInterval:TimeInterval = 0
let buttonNorth = SKSpriteNode(imageNamed: "Directional_Button")
let buttonSouth = SKSpriteNode(imageNamed: "Directional_Button")
let buttonEast = SKSpriteNode(imageNamed: "Directional_Button2")
let buttonWest = SKSpriteNode(imageNamed: "Directional_Button2")
var moveAtEndOfRelease:Bool = true
var isPressing = false
var currentState = MoveStates.n
override func didMove(to view: SKView) {
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
// Make sure you can get teh player from the scene file
if let somePlayer = self.childNode(withName: "player") as? SKSpriteNode {
player = somePlayer
// Set physics
player.physicsBody?.isDynamic = false
} else {
print("No player")
}
let widthHalf:CGFloat = self.view!.bounds.width / 2
let heightHalf:CGFloat = self.view!.bounds.height / 2
self.addChild(buttonNorth)
buttonNorth.position = CGPoint(x: -widthHalf + 80, y: -heightHalf + 100)
self.addChild(buttonSouth)
buttonSouth.position = CGPoint(x: -widthHalf + 80, y: -heightHalf + 40)
buttonSouth.yScale = -1
self.addChild(buttonWest)
buttonWest.position = CGPoint( x: -widthHalf + 30, y: -heightHalf + 70)
self.addChild(buttonEast)
buttonEast.position = CGPoint( x: -widthHalf + 130, y: -heightHalf + 70)
buttonNorth.xScale = 0.4
buttonNorth.yScale = 0.4
buttonSouth.xScale = 0.4
buttonSouth.yScale = 0.4
buttonSouth.zRotation = CGFloat(Double.pi)
buttonEast.xScale = 0.4
buttonEast.yScale = 0.4
buttonEast.zRotation = CGFloat(Double.pi)
buttonWest.xScale = 0.4
buttonWest.yScale = 0.4
}
override func update(_ currentTime: TimeInterval) {
//player.position = CGPoint(x: player.position.x + playerSpeedx, y: player.position.y + playerSpeedy)
if (isPressing) {
moveOnRelease()
}
}
func move(facing: Facing, x: CGFloat, y: CGFloat) {
let walkAnimation = SKAction(named: "walk\(facing)")!
let moveAction = SKAction.moveBy(x: x, y: y, duration: 1)
let group = SKAction.group([walkAnimation, moveAction])
// Run the actions
player.run(group)
}
func moveSide(facing: Facing, x: CGFloat) {
let walkAnimation = SKAction(named: "walk\(facing)")!
let moveAction = SKAction.moveBy(x: x, y: 0, duration: 1)
let group = SKAction.group([walkAnimation, moveAction])
// Run the actions
player.run(group)
}
func moveUpDown(facing: Facing, y: CGFloat) {
let walkAnimation = SKAction(named: "walk\(facing)")!
let moveAction = SKAction.moveBy(x: 0, y: y, duration: 1)
let group = SKAction.group([walkAnimation, moveAction])
// Run the actions
player.run(group)
}
func moveOnRelease() {
switch (currentState) {
case .n:
moveUpDown(facing: .Back, y: 1)
case .s:
moveUpDown(facing: .Front, y: -1)
case .e:
moveSide(facing: .Right, x: 1)
case .w:
moveSide(facing: .Left, x: -1)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in (touches ) {
let location = touch.location(in: self)
if (buttonNorth.frame.contains(location)) {
currentState = MoveStates.n
buttonNorth.texture = SKTexture(imageNamed: "Directional_Button_Lit")
isPressing = true
} else if (buttonSouth.frame.contains(location)) {
currentState = MoveStates.s
buttonSouth.texture = SKTexture(imageNamed: "Directional_Button_Lit")
isPressing = true
} else if (buttonEast.frame.contains(location)) {
currentState = MoveStates.e
buttonEast.texture = SKTexture(imageNamed: "Directional_Button2_Lit")
isPressing = true
} else if (buttonWest.frame.contains(location)) {
currentState = MoveStates.w
buttonWest.texture = SKTexture(imageNamed: "Directional_Button2_Lit")
isPressing = true
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if (moveAtEndOfRelease == true) {
buttonNorth.texture = SKTexture(imageNamed: "Directional_Button")
buttonSouth.texture = SKTexture(imageNamed: "Directional_Button")
buttonEast.texture = SKTexture(imageNamed: "Directional_Button2")
buttonWest.texture = SKTexture(imageNamed: "Directional_Button2")
//moveOnRelease()
isPressing = false
}
}
}
The reason it is stuck on the first frame is because the action is being called on every update i believe. You could check to see if the animation is already running, if so do not run it again.
To do this, for each run action give it a name.
So player.run(group) could be
player.run(group, withKey: "moveside"). Then, you can check to see if the action is already running or not like this if (player.action(forKey: "moveside") == nil). Finally, add in code to remove all other actions (like current movement or animations).
Putting it altogether:
if (player.action(forKey: "moveside") == nil) {
player.removeAllActions()
player.run(group, withKey: "moveside")
}

How to force on touch.location to work only in special place on screen?

that is my first question here so - Hello Word.
I have a small problem with my code. I want to force on this program to make balls appear only if you will touch over and equal y: 650 point and boxes to appear only if you will touch under y: 650 point. x position makes here no role.
That is my code:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let objects = nodes(at: location)
if objects.contains(editLabel) {
editingMode = !editingMode
} else {
if editingMode {
let size = CGSize(width: GKRandomDistribution(lowestValue: 16, highestValue: 128).nextInt(), height: 16)
let box = SKSpriteNode(color: RandomColor(), size: size)
box.zRotation = RandomCGFloat(min: 0, max: 3)
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOf: box.size)
box.physicsBody!.isDynamic = false
addChild(box)
} else {
let ball = SKSpriteNode(imageNamed: "ballRed")
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0)
ball.physicsBody!.contactTestBitMask = ball.physicsBody!.collisionBitMask
ball.physicsBody!.restitution = 0.4
ball.position = location
ball.name = "ball"
addChild(ball)
}
}
}
}
Looking forward for help :)
For me this worked:
ball.position = location
if (location.y < 500) {
ball.position.y = 500
}

Swift: Attemped to add a SKNode which already has a parent:

I know why I'm getting that error, but I can't figure out a way around it. I'm trying to have objects come appear and then be removed and the player should try to tap them before they're removed, but everytime the next node is about to appear it crashes. If i declare it inside its func then it all comes out but I can't tap on it...
Code:
let step = SKSpriteNode()
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
backgroundColor = UIColor.feelFreeToColor()
self.color = self.randomNumbersInt(3)
self.showBars()
self.showScore()
let spawn = SKAction.runBlock {
//self.color = self.randomNumbersInt(3)
self.showSteps()
}
let delay = SKAction.waitForDuration(1.5)
let spawnDelay = SKAction.sequence([spawn , delay])
let spawnDelayForever = SKAction.repeatActionForever(spawnDelay)
self.runAction(spawnDelayForever)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
var location = touch.locationInNode(self)
if self.nodeAtPoint(location) == step {
self.score += 1
}
}
}
func showSteps() {
let createSteps = SKAction.moveByX(0, y: -self.frame.height - 30 , duration: 10)
let removeSteps = SKAction.removeFromParent()
step.color = colors[randomNumbersInt(3)]!
step.size = CGSize(width: 275, height: 30)
step.position = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.75)
step.physicsBody = SKPhysicsBody(rectangleOfSize: step.size)
step.physicsBody?.categoryBitMask = Config.PhysicBodyType.Steps.rawValue
step.physicsBody?.affectedByGravity = false
step.physicsBody?.dynamic = false
step.zPosition = 1
step.runAction(SKAction.repeatActionForever(SKAction.sequence([createSteps, removeSteps])))
addChild(step)
}
In your showSteps function, declare the step node inside it, not at the top of your code, and also give it a name:
func showSteps() {
let step = SKSpriteNode()
...
step.name = "step"
step.color = colors[randomNumbersInt(3)]!
// etc
}
In your touchesBegan method, you have this if statement:
if self.nodeAtPoint(location) == step {
self.score += 1
}
You want to remove that node that you have hit, but now you can just check the name property like so:
if self.nodeAtPoint(location)?.name == "step" {
self.nodeAtPoint(location)?.removeFromParent()
self.score += 1
}
Please note that I am not super fluent in Swift, but I think you will probably need the ? in your if statement, as it might not exist (such as if you didn't tap on a specific node). Somebody more familiar with Swift is free to correct me.

SKLabel won't show up

Im making a flappy bird type game in swift using sprite kit. The game works fine but I'm trying to make a way to score the game so I set up a variable and SKLabel that adds on to itself whenever a pipe is about half way across the screen. However I cannot get the label to show up any help doing this here is my code:
// flappy rainbow sheep
//
// Created by Heather Arnold on 3/3/15.
// Copyright (c) 2015 ian arnold. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var bird = SKSpriteNode()
var pipeUpTexture = SKTexture()
var pipeDownTexture = SKTexture()
var PipeMoveAndRemove = SKAction()
let pipeGap = 225.0
var score: Int = 0
var scoreLabel: SKLabelNode = SKLabelNode(fontNamed:"System-Bold")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
score = 0
//Physics
self.physicsWorld.gravity = CGVectorMake(0.0, -10.0);
//Bird
var BirdTexture = SKTexture(imageNamed:"flappysheep")
BirdTexture.filteringMode = SKTextureFilteringMode.Nearest
bird = SKSpriteNode(texture: BirdTexture)
bird.setScale(0.5)
bird.position = CGPoint(x: self.frame.size.width * 0.35, y: self.frame.size.height * 0.6)
scoreLabel.position.x = 50
scoreLabel.position.y = view.bounds.height - 50
scoreLabel.text = "0"
scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
scoreLabel.hidden = false
self.addChild(scoreLabel)
bird.physicsBody = SKPhysicsBody(circleOfRadius:bird.size.height/4.0);
bird.physicsBody?.dynamic = true
bird.physicsBody?.allowsRotation = false
self.addChild(bird)
//off screen
//Ground
var groundTexture = SKTexture(imageNamed:"rainbowobstacle")
var sprite = SKSpriteNode(texture: groundTexture)
sprite.setScale(2.0)
sprite.position = CGPointMake(self.size.width/2.0, sprite.size.height/2.0)
self.addChild(sprite)
var ground = SKNode()
ground.position = CGPointMake(0, groundTexture.size().height)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, groundTexture.size().height * 2.0))
ground.physicsBody?.dynamic = false
self.addChild(ground)
//Pipes
//create the pipes
pipeUpTexture = SKTexture(imageNamed:"rainbowpipe")
pipeDownTexture = SKTexture(imageNamed:"rainbowpipe")
//move pipes
let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeUpTexture.size().width)
let movePipes = SKAction.moveByX(-2500, y: 0.0, duration: NSTimeInterval(0.01 * distanceToMove))
let removePipes = SKAction.removeFromParent()
PipeMoveAndRemove = SKAction.sequence([movePipes, removePipes])
//spwan pipes
let spawn = SKAction.runBlock({() in self.spawnPipes()})
let delay = SKAction.waitForDuration(NSTimeInterval(0.2))
let spawnThenDelay = SKAction.sequence([spawn, delay])
let spawnThenDelayForever = SKAction.repeatActionForever(spawnThenDelay)
self.runAction(spawnThenDelayForever)
let pipeUp = SKSpriteNode(texture:pipeUpTexture)
if (pipeUp.position.x + (pipeUp.size.width / 2) < self.view!.bounds.size.width / 2)
{
score++
}
scoreLabel.hidden = false
}
func spawnPipes(){
let pipePair = SKNode()
pipePair.position = CGPointMake(self.frame.size.width + pipeUpTexture.size().width * 2, 0)
pipePair.zPosition = -10
let height = UInt32(self.frame.size.height / 4)
let y = arc4random() % height + height
let pipeDown = SKSpriteNode(texture:pipeDownTexture)
pipeDown.setScale(2.0)
pipeDown.position = CGPointMake(0.0, CGFloat(y) + pipeDown.size.height + CGFloat(pipeGap))
pipeDown.physicsBody = SKPhysicsBody(rectangleOfSize:pipeDown.size)
pipeDown.physicsBody?.dynamic = false
pipePair.addChild(pipeDown)
let pipeUp = SKSpriteNode(texture:pipeUpTexture)
pipeUp.setScale(2.0)
pipeUp.position = CGPointMake(0.0, CGFloat(y))
pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)
pipeUp.physicsBody?.dynamic = false
pipePair.addChild(pipeUp)
pipePair.runAction(PipeMoveAndRemove)
self.addChild(pipePair)
}
class GameScene: SKScene {
let bird = SKSpriteNode()
var gameOver = false
override init(size: CGSize) {
super.init(size: size)
self.bird.position = CGPoint(x: 0, y: 0)
self.addChild(self.bird)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func endGame(){
// restart the game
let gameScene = GameScene(size: self.size)
self.view!.presentScene(gameScene)
}
override func update(currentTime: NSTimeInterval) {
// our bird doesnt intersect the frame,
// we use gameOver bool so we dont call endGame more than once
if !self.frame.intersects(self.bird.frame) && !self.gameOver{
self.gameOver = true
self.endGame()
}
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
bird.physicsBody?.velocity = CGVectorMake(0, 0)
bird.physicsBody?.applyImpulse(CGVectorMake(0, 8))
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
Your label might be covered over by another image. Try setting the SKLabelNode zPosition property to a higher value. Perhaps something like 900.
Try setting the zPosition of the label to one.
scoreLabel.zPosition = 1
This should make the node appear even if another node passes over it.
Here are two other functions that may assist you also:
scoreLabel.color = UIColor.blackColor()//set color to black - you can use any almost color here
scoreLabel.fontSize = 32//changes font size to make label bigger/smaller