Chak Wing Mak
Chak Wing Mak

Reputation: 41

How to inherit the SKspritenode and create by self.childNode

I have a problem dealing with inheritance for the skspritenode I have created a skspritenode in the scence and want to inherit the sksprite to a car class

Car Class

class Car : SKSpriteNode {
  var CurrentLocation = 1
}

GameScene

class GameScene: SKScene {
    var leftCar = Car()

    func setUp() {
       leftCar = self.childNode(withName: "leftCar") as! SKSpriteNode
    }
}

I dont know what the meaning of Cannot assign value of type 'SKSpriteNode' to Car and how to reslove this error, thankyou for your help

Upvotes: 1

Views: 116

Answers (1)

Kamran
Kamran

Reputation: 15258

leftCar is of type Car so compiler is complaining to cast childNode as Car instead of SKSpriteNode shown below.

func setUp() {
   if let car = self.childNode(withName: "leftCar") as? Car {
      leftCar = car
   }
}

BTW, you already initialized leftCar in the same GameScene so you can simply use that instead of assigning it again.


Set custom class Car in GameScene.sks for leftCar node as shown in below image,

enter image description here

Upvotes: 1

Related Questions