I'm trying to give my main character a Custom Class so that I can define all his behaviors inside the defined class.
I already did something like this, by using protocols:
protocol CustomNodeEvents{
func didMoveToScene()
}
This protocol is in the GameScene file, before the class starts. Then I call the function like this in the GameScene class:
override func didMove(to view: SKView) {
if let customnode = player as? CustomNodeEvents{
customnode.didMoveToScene()
}
}
Where the player is defined as:
player = self.childNode(withName: "//player") as! SKSpriteNode
also inside the didMove(to view: SKView) function.
Now I created another file (my custom class file) and I write:
import SpriteKit
class Custom: SKSpriteNode, CustomNodeEvents{
func didMoveToScene() {
print("It Worked")
}
}
I don't have any errors but it doesn't actually run the block of code inside my Custom class (in the GameScene.sks file I already attached the class to the player).
My question is how can I make it work? And the second question is, is this the best way to define a Custom Class and "connect" it with other classes?
EDIT:
class GameScene: SKScene {
var player: SKSpriteNode!
override func didMove(to view: SKView) {
player = self.childNode(withName: "//player") as! SKSpriteNode
if let customnode = player as? CustomNodeEvents{
customnode.didMoveToScene()
}
Not sure where the problem is, but this code works for me:
import SpriteKit
protocol CustomNodeEvents
{
func didMoveToScene()
}
class Custom : SKSpriteNode,CustomNodeEvents
{
func didMoveToScene()
{
print("It Worked")
}
}
class GameScene:SKScene{
var player : SKSpriteNode!
override func didMove(to view: SKView) {
player = self.childNode(withName: "//player") as! SKSpriteNode
if let customnode = player as? CustomNodeEvents
{
customnode.didMoveToScene()
}
else
{
print("Error creating node")
}
}
}
I can only conclude that there is an issue in the sks file, and the player we are grabbing is not the player you are looking for, or the player is not of class Custom. (Note I placed the player sprite at the top most level of the scene)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With