Reputation: 37
I implemented a class subclassing SKSpriteNode with an additional property. Then I created an instance of it and attempted to modify its property's value each frame but I encountered an error.
Are there any ways to handle this?
import SpriteKit
import GameplayKit
class SomeSprite: SKSpriteNode {
var direction: CGVector = CGVector(dx: 0, dy: 0)
convenience init() {
self.init(imageNamed: "imgSprite")
}
}
class GameScene: SKScene {
override func didMove(to view: SKView) {
//Create a sprite instance
var sampleSprite = SomeSprite()
sampleSprite.name = "Sprite"
sampleSprite.zPosition = 1
sampleSprite.position = CGPoint(x: 100, y: 100)
sampleSprite.direction = CGVector(dx: 10, dy: 10)
sampleSprite.setScale(1)
self.addChild(sampleSprite)
}
override func update(_ currentTime: TimeInterval) {
//Calculate before rendering frame
self.enumerateChildNodes(withName: "Sprite") { (sprite, stop) in
sprite.position = CGPoint(x: 150, y: 150) //This works properly
sprite.direction = CGVector(dx: 15, dy: 15) //Error: Value of type SKNode has no member 'direction'
}
}
}
Upvotes: 1
Views: 50
Reputation: 1339
The method enumerateChildNodes return a list of SKNodes
You have to try to cast the object to your class SomeSprite
override func update(_ currentTime: TimeInterval) {
//Calculate before rendering frame
self.enumerateChildNodes(withName: "Sprite") { (sprite, stop) in
sprite.position = CGPoint(x: 150, y: 150) //This works properly
if let someSprite = sprite as? SomeSprite {
someSprite.direction = CGVector(dx: 15, dy: 15)
}
}
}
Upvotes: 1