SpriteKit - create sprite in Gamescene.sks and reference in another class

Viewed 989

I know I can use the following in GameScene.swift to reference a sprite I created in the level editor:

ball = childNode(withName: "ball") as? SKSpriteNode

what if I want to reference that ball from a Ball class? Below is what I thought would work. I was wrong. In the level editor I've given the ball the custom class of Ball.


1. I've created a ball sprite in GameScene.sks and assigned it the Custom Class of Ball:

sprite in GameScene.sks

  1. This is my custom Ball class. (You can ignore the contents, because it doesn't work.)

    class Ball: SKSpriteNode {
    
      init() {
        let size = CGSize(width: 35, height: 35)
        super.init(texture: nil, color: UIColor.clear, size: size)
    
      }
    
      required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
      }
    
      func moveBall() {
        self.position = CGPoint(x: 50, y:50)
      }
    }
    
  2. Then, in GameScene.swift, I'd like to use the Ball function moveBall() I defined.

    class GameScene: SKScene {
      var ball = Ball()
      override func didMove(to view: SKView) {
        ball.moveBall()
      }  
    }
    
2 Answers
Related