Respawning a node after it's been deleted? Swift Spritekit - swift

Once a node is removed, I'm needing to respawn it back to it's original position.
I've tried a few things:
1) In the didBeginContact where it gets deleted, I've just added an addChild() after the delete, but that just added it back where it was, making it look like it just paused in place
2) When it dies, I'm setting a variable to 0, and I created a function that adds the node back where it starts out, and then I set up an if statement that looks like :
if playerLife == 0 {
spawnPlayer()
}
and the player life gets set to 0 down in my didBeginContact. Don't know if that even makes sense
3) I tried slapping all of this down in the didBeginContact
The ball is either freezing when I try to addchild directly back right after I delete it in the DidBegin, otherwise it gets deleted and never is respawned.

Try moving your code inside of the update function. also in your spawnPlayer function make sure to add your node if node.parent == nil
override func update(currentTime: NSTimeInterval) {
if playerLife == 0 {
spawnPlayer()
}
}

Related

Weird behavior of SKAction on children

Well, my aim is to extract the content of a SKScene and then run some actions to their node:
func loadSceneNodes() {
let loadedScene = SKScene(fileNamed: "newScene.sks")
// Reads the content of the "Content" node in the newScene.sks
let content = loadedScene!.childNode(withName: "Content") as! SKSpritenode
// I move the content to self
// (THANKS Knight0fDragon for suggestion)
content.move(toParent: self)
// Forces the unpause
self.isPause = false
// Try to run a test action on the node
content.run(.rotate(byAngle: 90, duration: 2.0)) {
print("DONE")
}
print(content.hasActions()) // DEBUG -> it prints TRUE
}
What happens is that I successful read the content and it shows on the scene, but the actions aren't shown even if hasActions() results true.
I found out something very interesting by playing with breakpoints and the debug console. content.hasActions() returns true because all of the SKActions get into a stack:
They seem like freeze because if I assign more actions, they will get stack in the pile one by one without getting run.
Only once I quit the breakpoint (or whether I pause and then play the application through xCode) everything is executed. Just like the app "needs" a refresh.
Use moveToParent on your sknode instead of addChild on your parent node to avoid the need to create a copy.
Ensure the isPaused state is set to false, you may be copying at a time where it is true

Increase Node Speed with SKPhysicsBody linearDamping Swift 4

I have the below class being called from my GameScene
func update(_ currentTime: TimeInterval)
Since it's being called there, my class is being called every second which leads me to this. I currently have my self.physicsBody?.linearDamping = 0.6 but how would I increase that number so I can also increase the speed? I was going to use another Timer till I realized my SKSpriteNode class is being called every second. Not too sure how to go about this, any ideas? I basically want to decrease that number every 2.0 seconds without letting the update function get in the way.
Any time you want to do something at regular time intervals in a sprite-Kit game, you can implement this as follows:
First declare 2 properties (in your class but outside all the function definitions)
var timeOfLastThing: CFTimeInterval = 0.0
var timePerThing: CFTimeInterval = 2.0 // How often to do the thing
( if the thing you want to do every 2 seconds is spawn a monster, then you might call these timeOfLastMonsterSpawn and timePerMonsterSpawn, but it's up to you)
Then, in Update, check to see if the timePerThing has been exceeded. If so, call your doThing function which does what you need it to and then reset the time since the last call:
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if (currentTime - timeOfLastThing > timePerThing) {
doThing()
self.timeOfLastThing = currentTime
}
}
func doThing() {
// Your spawn code here
}
The advantage of making the doThing a separate function (as opposed to it being in line in update())is that you can call it from didMoveToView or any other place to spawn objects outside of the normal time-controlled cycle.
You can change the value of timePerThing as necessary to control the rate at which things happen.
You could also look into creating an SKAction that runs doThing at specified time intervals, but I think to change the rate at which objects are spawned, you'll have to delete and re-create the SKAction, which you could do this in a setter for timePerThing.
You shouldn't really use NSTimer in SpriteKit, as the SpriteKit engine will be unaware of what the timer is doing and can't control it (one example is that the timer keeps running and doing stuff even if you set the scene to paused).

How to control the speed of nodes in SpriteKit

I have a bunch of objects (SKNode) starting from the top of the screen 'falling' to the bottom via SKAction.move(to:duration:) and node.run(moveAction). In addition I have node in the center of the screen with its own physics body that can be dragged side to side with touch input. I can detect collisions fine, but I was wondering if there was a paradigm for 'pausing' all the objects while the center node is contact with any of the objects. Additionally, I want to able to move the center node while the other objects are 'paused' so I can move it out of the way and then let the objects resume their motion. I figured I could probably iterate through all the existing objects and set their isPaused property, but I am unsure how the app would know when the center node is no longer 'colliding' so I can toggle the property back.
To pause things, you will have to detect the contact in didBegin() , tofill some array with nodes that should be paused and finally to pause the nodes. Actual pausing could be done in didSimulatePhysics() for example. To pause all the nodes you could use
self.enumerateChildNodesWithName("aName") {
node, stop in
// do something with node or stop
}
or use children property of a node and loop through it (eg. to loop through the container of your nodes that should be paused).
Also you can pause certain action with:
if let action = square.actionForKey("aKey") {
action.speed = 0
}
and unpause it with action.speed = 1, or make it slow-mo with action.speed = 0.5
To slow down physics simulation, there is a property called physicsWorld.speed (determines the rate at which the simulation runs).
Oh boy, things sure do get complicated. Every thing that Whirlwind says is correct, but to iterate through every node on the scene can become burdensome.
Instead, I recommend creating a special subclass for SKNode. Now this special class is needed due to a bug caused by apples framework
class UserPausableNode : SKNode
{
public var userPaused = false
{
didSet
{
super.isPaused = userPaused
}
}
override var isPaused : Bool
{
get
{
return userPaused
}
set
{
//Yes, do nothing here
}
}
}
The reason why we need to do this is because whenever isPaused is called, it iterates to all children and sets the child isPaused property.
This becomes a problem when scene pauses and unpauses, as it will change the pause state of the children, which we do not want to be doing.
This class prevents the isPaused variable from changing.
Now that this class exists, what we want to do is add it to the scene, and add all moving nodes to this new node.
Since all of the nodes are on this new node, all we need to do is set the userPaused to true, and this will stop all nodes.
Now make sure the node you are moving is not a part of this branch, it should be outside so that you could move it.
Example
class GameScene : SKScene
{
var userBranch = UserPausableNode()
func didMove(to view:SKView)
{
self.addChild(userBranch)
//generetedChildren are nodes that you create that you plan on pausing as a group
for generatedChild in generatedChildren
{
userBranch.addChild(node)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//this will pause and unpause based on opposite of previous state
userBranch.userPaused = !userBranch.userPaused
}
}

sceneDidLoad Running Twice

When I run my program. The code I put into "override func sceneDidLoad()" runs two times.
E.g.
Note: I have no idea why this picture is not uploading, but it shows "spawn" happening twice.
This code should only run once when "sceneDidLoad()" is called.
Here is the code for the "sceneDidLoad" function, and for the "testSpawn()" function (which is the specific one that gave the duplicated printout).
class GameScene: SKScene {
var mapTerrain: SKTileMapNode!
override func sceneDidLoad() {
cam = SKCameraNode()
cam.xScale = 1
cam.yScale = 1
//do zoom by change in scale in pinch. (E.g. if they start out 5 units apart and end up 15 units apart, zoom by a factor of 3
self.camera = cam
self.addChild(cam)
cam.position = CGPoint(x: 100, y: 100)
setupLayers()
loadSceneNodes()
setUpUI()
testSpawn()
//print("\(self.frame.width), \(self.frame.height)")
}
func testSpawn(){
let RedLegion = legion(texture: textureRedLegion, moveTo: nil, tag: 1, health: 2)
RedLegion.position = mapTerrain.centerOfTile(atColumn: 0, row: 0)
RedLegion.team = "Red"
unitsLayer.addChild(RedLegion)
legionList.append(RedLegion)
print("spawn")
}
}
Note: Not all of the code is here (like "setUpLayers()"), if needed I can supply it, I just do not think it is neccessary.
Search your whole document for "print("spawn")" just to make sure that is the only time you call the function. Also check for "testSpawn()" to make sure it is only called once. Additionally, instead of relying on this print to count how many times the sceneDidLoad runs, place a print directly within your sceneDidLoad. Finally, check to make sure you are not creating the scene twice.
I've also seen this and submitted a bug report but apple responded saying that it is intended behavior. Apple said that it creates a dummy scene and then creates the actual scene. Before it runs the second time it gets rid of anything done the first time so you shouldn't get any errors from it. The bug is really hard to reproduce, one of my friends working off the same repository that I was but did not experience the bug.
I changed sceneDidLoad to didMoveToView:(SKView *)view if you are looking for a solution to this. Make sure you xcode is up to date.

Very Basic Node Removal in Swift

I found some other questions about node removal in swift, but none of them seemed to be quite relevant to my issue.
I just want to do a basic node removal, for example:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent){
let covernode1 = SKSpriteNode(imageNamed: "tester")
covernode1.position = CGPointMake(100.0, 600.0)
for touch: AnyObject in touches {
if self.nodeAtPoint(location) == self.fake {
button1++
button2++
}
if(button1 == 1 && button2 == 1){
addChild(covernode1)
}
if(button1 == 2 && button2 == 2){
//THIS IS WHERE I WANT TO REMOVE THE NODE
}
I have tried
covernode1.removeFromParent()
but to no avail.
The code runs the addChild part fine, but removal seems to be a problem. I even tried just changing the position of the node so it's off screen, with something like
covernode1.position = CGPointMake(-100.0, -600.0)
This did not work either.
Thank you.
Unfortunately I don't have enough reputation to comment on your original question, so this may not be an "answer" per se, but I'll try and diagnose what I think is going on, and hopefully you can clear up some points for me.
The covernode1 that you are trying to remove from the parent view in your if statement may be a different node than the one you added to the view when you called addChild(covernode1)
I think this is the case because when you say you are using covernode1.position = CGPointMake(-100.0, -600.0) and it still does not work, that makes me think that is a completely different SKNode object.
Instead, try declaring covernode1 outside of the function as a class variable. That way, when you actually instantiate it and refer to it in the function, it is grabbing the correct node you are looking for. Let me know if any of this helps. I'll edit the answer when I know a bit more from your response.
Also, are your button1 and button2 vars originally set to 1?
EDIT: Another question: Are you receiving any error when calling .removeFromParent() or is just "not doing anything"?
One simple thing you could do (kind of cheating but it will work) is to hide the node using
covernode1.hidden = true
Note
Also make sure the if statement actually runs because I don't know why the things you tried should not work. To test that, place a println("log") in the if block.
Hope that helps :)
From button1 and button2, I think you are trying to do this: On the first click, you add a SKNode. On the second click, you want to remove the SKNode.
Thus on the second click your let covernode1 = SKSpriteNode(imageNamed: "tester") is a different instance although it has the same variable name ! Thus the instance on the second click is not removable since it was not added to anything.
Try this,
if(button1 == 1 && button2 == 1){
addChild(covernode1)
self.tempChildCount = count(self.children) //tempChildCount is an integer
}
if(button1 == 2 && button2 == 2){
let childNode = self.children[self.tempChildCount - 1 ] as! SKNode
self.removeChildrenInArray([childNode])
}