Removing sprites/labels slow in swift (removeallchildren) - ios

I am adding sklabelnodes and skspritenodes to the scene with these functions:
var levelnode = SKSpriteNode()
var labelLevel = SKLabelNode(fontNamed: "Courier-Bold")
func addlevels(){
var level = score + 1
if (level > 0){
sprite()
levelnode.position = CGPointMake(frame.size.width / 2.2, -frame.size.height/15.6 - frame.size.height/17.6)
levelnode.name = "1"
addChild(levelnode)
sklabel()
labelLevel.text = ("1")
labelLevel.position.x = levelnode.position.x - (levelnode.size.width/40)
labelLevel.position.y = levelnode.position.y - (levelnode.size.width/6)
labelLevel.name = "1"
addChild(labelLevel)
}
if (level > 1){
sprite()
levelnode.position = CGPointMake(frame.size.width / 1.42 - frame.size.width/100, -frame.size.height/10 - frame.size.height/17.6)
levelnode.name = "2"
addChild(levelnode)
sklabel()
labelLevel.text = ("2")
labelLevel.position.x = levelnode.position.x - (levelnode.size.width/40)
labelLevel.position.y = levelnode.position.y - (levelnode.size.width/6)
labelLevel.name = "2"
addChild(labelLevel)
}
// this goes on and on till level 25
}
func sprite(){
levelnode = SKSpriteNode(imageNamed: "levelnode")
levelnode.size.width = frame.size.width / 8
levelnode.size.height = levelnode.size.width
levelnode.zPosition = 1
}
func sklabel(){
labelLevel = SKLabelNode(fontNamed: "Courier-Bold")
labelLevel.zPosition = 2
labelLevel.fontColor = SKColor.blackColor()
labelLevel.fontSize = frame.size.height / 35
}
When I am changing the scene, the sprites and labels are removed from the willmovefromview function:
override func willMoveFromView(view: SKView) {
removeAllChildren()
}
but this is taking too slow if I compare it with other scenes where even more skspritenodes are added..
I think It has to do with the functions where I add the sprites and labels, but what is wrong about it?
EDIT:
the function that takes me back too the menu:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
errint = false
for touch: AnyObject in touches {
let location: CGPoint! = touch.locationInNode(self)
let nodeAtPoint = self.nodeAtPoint(location)
if (nodeAtPoint.name != nil) {
if nodeAtPoint.name == "menu" {
removeallAction()
removeAllChildren()
var scene1 = GameMenuScene(size: self.size)
scene1.button = self.button
scene1.button2 = self.button2
scene1.button3 = self.button3
scene1.viewController = self.viewController
let transition = SKTransition.moveInWithDirection(SKTransitionDirection.Left, duration: 0.75)
self.view?.presentScene(scene1, transition: transition)
}
}
}
}

Doesn't transitioning to another scene deallocate the current scene?
And if that scene is deallocated, then there's no need for the nodes and such to be removed...
Could you do me a favor, and transition out without removing the children and actions, then transition back in and see if it matters??
Anyway, speed is trivial if you're testing on the simulator... the simulator really only simulates opengl, the core of SpriteKit.
Please try it on your device.
BTW, I'm not sure of stuff but nobody seemed to have answered you so I tried...
EDIT:
HOLY MOTHER OF GOD WHY DIDN'T I SEE THE TIMESTAMP IT WAS ASKED TWO MONTHS AGO.
Too late now I guess... but to anybody reading this, don't answer questions at 2 am.

Related

Is there a way to add action to all the created nodes except one node in swift?

I want to add an action for all nodes on the scene except one or two nodes.
Or, I would like to find a way to access to all nodes with a different way of using the "name" method.
This not the complete game but I do not want to use the "name" method because every square has different name.
import SpriteKit
import GameplayKit
var Score = 0
class GameScene: SKScene {
let SquareSide = 100
var touchedNode = SKNode()
var touchLocation = CGPoint()
let ScoreLabel = SKLabelNode()
let squareNumber = 0
override func didMove(to view: SKView) {
CreatSquares()
}
func CreatSquares(){
let square = SKShapeNode(rect: CGRect(x: Int(arc4random_uniform(UInt32(self.frame.width))), y: Int(arc4random_uniform(UInt32(self.frame.height))), width: SquareSide, height: SquareSide))
if Score <= 10{
square.fillColor = UIColor.orange}
else{
square.fillColor = UIColor.blue
}
square.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: square.frame.width, height: square.frame.height), center: CGPoint(x: square.position.x, y: square.position.y))
square.physicsBody?.affectedByGravity = false
square.physicsBody?.allowsRotation = false
square.physicsBody?.categoryBitMask = 0
square.name = "square\(number)"
number++
self.addChild(square)
}
}
func CreatScoreLabel(){
let ScoreLabel = SKLabelNode()
ScoreLabel.text = "Your Score is:\(Score)"
ScoreLabel.position = CGPoint(x: self.frame.width/2, y: self.frame.height - 50)
ScoreLabel.color = UIColor.white
self.addChild(ScoreLabel)
}
func updatScore(){
ScoreLabel.text = "Your Score is:\(Score)"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
touchLocation = touch.location(in: self)
touchedNode = self.atPoint(touchLocation)
if touchedNode.name == "square"{
Score += 1
touchedNode.removeFromParent()
}
}
}
override func update(_ currentTime: TimeInterval) {
updatScore()
}
As explained by Confused I think you forgot the real power of enumerateChildNodes(withName:
Indeed, about the name:
The name to search for. This may be either the literal name of the
node or a customized search string. See Searching the Node Tree.
This means that you also could do:
self.enumerateChildNodes(withName: "//square*") { node, _ in
// node is equal to each child where the name start with "square"
// in other words, here you can see square0, square1, square2, square3 etc...
if node.name == "square3" {
// do whatever you want with square3
}
}
// specifies that the search should begin at the root node and be performed recursively across the entire node tree. Otherwise, it performs a recursive search from its current position.
* means that the search matches zero or more characters.
The easiest way to do this is to add all the nodes you want to add the actions to into an array, then iterate over that array, adding actions when you want/need.
This has a memory hit if your objects are huge and complex, but is the most organised and rapid way to do it without using .name.
And is far faster and easier than messing around through your node hierarchy with enumerateChildNodes... etc

SKSpriteNode UserInteractionEnabled Not Working

I've looked everywhere but nothing works. Thought I would just ask the question myself. I'm creating a little game in iOS 9 using SpriteKit. My game is going to have left and right controller buttons to move the player sprite. I add the SKSpriteNodes for the directional pads as follows
At the top of the main scene I put:
private var leftDirectionalPad = SKSpriteNode(imageNamed: "left")
private var rightDirectionalPad = SKSpriteNode(imageNamed: "right")
Then I run a method called prepareDirectionalPads
func prepareDirectionalPads() {
// left
self.leftDirectionalPad.position.x = self.size.width * directionalPadLeftXPositionMultiplier
self.leftDirectionalPad.position.y = self.size.height*directionalPadYPosition
self.leftDirectionalPad.size.width = self.leftDirectionalPad.size.width/directionalPadSizeReductionMultiple
self.leftDirectionalPad.size.height = self.leftDirectionalPad.size.height/directionalPadSizeReductionMultiple
self.leftDirectionalPad.name = "leftDirectionalPad"
self.leftDirectionalPad.alpha = directionalPadAlphaValue
self.leftDirectionalPad.zPosition = 1
self.addChild(leftDirectionalPad)
self.leftDirectionalPad.userInteractionEnabled = true
// right
self.rightDirectionalPad.position.x = self.leftDirectionalPad.position.x*directionalPadSpacingMultiple
self.rightDirectionalPad.position.y = self.size.height*directionalPadYPosition
self.rightDirectionalPad.size.width = self.rightDirectionalPad.size.width/directionalPadSizeReductionMultiple
self.rightDirectionalPad.size.height = self.rightDirectionalPad.size.height/directionalPadSizeReductionMultiple
self.rightDirectionalPad.name = "rightDirectionalPad"
self.rightDirectionalPad.alpha = directionalPadAlphaValue
self.rightDirectionalPad.zPosition = 1
self.addChild(rightDirectionalPad)
self.rightDirectionalPad.userInteractionEnabled = true
}
I clearly set userInteractionEnabled for each SKSpriteNode to true. Then, in touches began I wrote...
override func touchesBegan(let touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
var touch = touches.first! as UITouch
var location = touch.locationInView(self.view)
var node = nodeAtPoint(location)
print("Touched")
}
Note: I have also tried var location = touch.locationInNode(self) but that doesnt work either.
I then run the app (either on my xCode Simulator or iPhone 6). If I touch on the SKNodes, nothing happens. Nothing is printed to the console. However, if I touch anywhere else on the screen, I get "touched" printed to the screen.
What am I doing wrong? I want to detect the touch on the pads so I can move the player sprite accordingly. It might be something really stupid I'm forgetting to do. Thanks for your time and patience. Much appreciated.
Figured it out. So apparently self.leftDirectionalPad.userInteractionEnabled = true does not work. It needs to be self.leftDirectionalPad.userInteractionEnabled = false, which is very counter-intuitive. I don't get it but it works now. touchesBegan responds to when the user touches the SKSpriteNode.
let touch = touches.first! as UITouch
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
if(node.name == leftDirectionalPad.name)
{
print("left")
}
else if (node.name == rightDirectionalPad.name)
{
print("right")
}

Sprite issue when responding to touch event in SpriteKit Swift

I have loaded two checkbox sprites on the screen. The image to load the sprite initially in an unchecked checkbox. Then I expect to click on one checkbox and replace the image with another checked checkbox image. The code I have written behaves very strangely where the checked checkbox image never appears.
I have two class properties:
var check1: SKSpriteNode = SKSpriteNode (imageNamed: "unchecked.png")
var check2: SKSpriteNode = SKSpriteNode (imageNamed: "unchecked.png")
I am calling generateCheckboxex() method from didMoveToView(view: SKView)
func generateCheckboxes()
{
self.check1.position = CGPointMake(self.size.width * 0.75, self.size.height * 0.84)
self.check1.setScale(0.15)
self.check1.name = "check1"
self.addChild(self.check1)
self.check2.position = CGPointMake(self.size.width * 0.75, self.size.height * 0.75)
self.check2.setScale(0.15)
self.check2.name = "check2"
self.addChild(self.check2)
}
This is my touchBegan method code:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch = touches as! Set<UITouch>
var location = touch.first!.locationInNode(self)
var node = self.nodeAtPoint(location)
// If next button is touched, start transition to second scene
if node.name == "check1" {
//self.check1.texture = SKTexture(imageNamed: "checked.png")
var texAction = SKAction.setTexture(SKTexture(imageNamed: "checked.png"))
self.check1.runAction(texAction)
//self.check2.texture = SKTexture(imageNamed: "checked.png")
self.check2.runAction(texAction)
}
if node.name == "check2" {
self.check1.texture = SKTexture(imageNamed: "unchecked.png")
self.check2.texture = SKTexture(imageNamed: "checked.png")
}
}
Please help me and let me know if I'm approaching it in the wrong manner, thanks.
EDIT: Admins please close this question, this exact same code works for me now. Maybe it was an issue with the sprites themselves. Thanks!

Removing a sprite in an if statement with SpriteKit

I want to make a game where every time a user touches, it switches between one of two "states". In order to keep track of touches, I made a variable called userTouches, which changes from true to false each time a user touches. I want to make it so that if numberOfTouches is true, it updates the texture to state0; if it's false, it updates the texture to state1. Pretty much just toggling between state0 and state1 for each touch.
var userTouches: Bool = true
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
userTouches = !userTouches
}
let centered = CGPoint(x: size.width/2, y: size.height/2)
let state0 = SKTexture(imageNamed:"state0")
let state1 = SKTexture(imageNamed:"state1")
var activeState: SKSpriteNode = SKSpriteNode(texture: state0)
//Add new state0 if it's odd, remove old state0 if it's not.
if userTouches == true {
activeState.texture = state0
println("IT'S TRUE")
} else {
activeState.texture = state1
println("IT'S FALSE")
}
self.addChild(activeState)
activeState.name = "state0"
activeState.xScale = 0.65
activeState.yScale = 0.65
activeState.position = centered
}
When I run the code, the new textures are added according to the conditions, but the old ones are still there. They are being added as new spritenodes in the scene. I do not want this. I was expecting it to simply switch between the textures (state0 and state1) of the activeState spritenode depending on my boolean variable. How can I have my code toggle between textures each time a user taps, instead of piling new spritenodes on top of one another?
Each time you create a new object, change its texture (a new object`s texture, but not the texture of object which was set up last time) and add it to the scene. That's why new objects are added and nothing happens with the old objects.
Do this and it will solve your problem:
Create textures and SKSpriteNode object outside the touchesBegan function
If you have no init at your scene, create SKSpriteNode object at didMoveToView function for example and add it to scene
Then in touchesBegan function only set texture to SKSpriteNode object
it would look something like this:
class GameScene: SKScene {
...
let state0 = SKTexture(imageNamed:"state0")
let state1 = SKTexture(imageNamed:"state1")
var activeState: SKSpriteNode?
...
override func didMoveToView(view: SKView) {
let centered = CGPoint(x: size.width/2, y: size.height/2)
activeState = SKSpriteNode(texture: state0)
self.addChild(activeState!)
activeState!.name = "state0"
activeState!.xScale = 0.65
activeState!.yScale = 0.65
activeState!.position = centered
}
...
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if userTouches {
activeState!.texture = state0
} else {
activeState!.texture = state1
}
}
...
}

See if SKShapeNode touched?: How to Identify node?

I am doing a small for fun project in Swift Xcode 6. The function thecircle() is called at a certain rate by a timer in didMoveToView(). My question is how do I detect if any one of the multiple circle nodes on the display is tapped? I currently do not see a way to access a single node in this function.
func thecircle() {
let circlenode = SKShapeNode(circleOfRadius: 25)
circlenode.strokeColor = UIColor.whiteColor()
circlenode.fillColor = UIColor.redColor()
let initialx = CGFloat(20)
let initialy = CGFloat(1015)
let initialposition = CGPoint(x: initialx, y: initialy)
circlenode.position = initialposition
self.addChild(circlenode)
let action1 = SKAction.moveTo(CGPoint(x: initialx, y: -20), duration: NSTimeInterval(5))
let action2 = SKAction.removeFromParent()
circlenode.runAction(SKAction.sequence([action1, action2]))
}
There are many problems with this.
You shouldnt be creating any looping timer in your games. A scene comes with an update method that is called at every frame of the game. Most of the time this is where you will be checking for changes in your scene.
You have no way of accessing circlenode from outside of your thecircle method. If you want to access from somewhere else you need to set up circlenode to be a property of your scene.
For example:
class GameScene: BaseScene {
let circlenode = SKShapeNode(circleOfRadius: 25)
You need to use the method touchesBegan. It should have come with your spritekit project. You can detect a touch to your node the following way:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// detect touch in the scene
let location = touch.locationInNode(self)
// check if circlenode has been touched
if self.circlenode.containsPoint(location) {
// your code here
}
}
}

Resources