Reputation: 189
I'm trying to teach myself Sprite Kit and Swift. What I'm trying to do is access a child node from an ArcheryScene.sks file and affect that child from the ArcheryScene.swift file. For Example: In my ArcheryScene.swift file I have added this line of code: let scene = SKScene(fileNamed: "ArcheryScene")
.
This compiles fine and when I say println(scene)
, it correctly prints the scene I want it to print, this is how I know that ArcheryScene.sks is truly in my scene
variable. After this, I access a child from that scene by adding this line of code: let ballChild = scene.childNodeWithName("Ball")
. When I use println(ballChild)
, it prints the correct child, letting me know that the variable truly contains Ball child that is in ArcheryScene.sks. And now to my problem...
Why can't I say things in my ArcheryScene.swift file like:
ballChild?.physicsBody?.affectedByGravity = false
or
ballChild?.position.x = self.frame.size.width / 2
or
let move = SKAction.moveByX(40, y: 0, duration: 5.0)
ballChild?.runAction(move)
All of this code will compile without errors but when I run the game, the Ball is not affected at all. Also, if I run ballChild?.position.x = self.frame.size.width / 2
and then print the ballChild position, it will show up as x: 512, which is what it should be, but still when I run the game, the Ball is not affected. This is really confusing to me and I'd just like to figure out what is going on. Any suggestions would be appreciated, thank you.
Upvotes: 1
Views: 1033
Reputation: 6612
When you write your following line :
let scene = SKScene(fileNamed: "ArcherySceneSKS")
You are creating a new scene. So the ballChild
you are accessing is another one (not the one inside your self
(ArcheryScene class)).
If you ArcheryScene
class is properly instantiated, can't you access the ball by doing like so ?
let ballChild = self.childNodeWithName("Ball")
Let me know if it helped.
Upvotes: 1
Reputation: 114992
If you look at the definition of Class ArcheryScene
you will see it is a subclass of SKScene
- so the class you are coding in is already your scene. The UIViewController
subclass in your project has loaded ArcheryScene.sks
and associated it with an instance of ArcheryScene
.
When you subsequently say let scene=SKScene(fileName:"ArcheryScene.sks")
you are actually creating a new instance of the scene that isn't presented into your SKView. You then modify the ball in that scene, but nothing happens as this is not the ball that is visible.
Instead you should say
let ballChild=self.childNodeWithName("Ball")
if (ballChild? != nil) {
let move=SKAction.moveByX(50 y:10 duration:10.0)
ballChild!.runAction(move)
}
Upvotes: 4