Ищете способы обновить свойство экземпляра для каждого кадра - PullRequest
1 голос
/ 11 марта 2020

Я реализовал подклассы класса SKSpriteNode с дополнительным свойством. Затем я создал его экземпляр и попытался изменить значение его свойства в каждом кадре, но обнаружил ошибку.

Есть ли способы справиться с этим?

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'
        }
    }
}

1 Ответ

1 голос
/ 11 марта 2020

Метод enumerateChildNodes возвращает список SKNodes

Вы должны попытаться привести объект к вашему классу 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)
            }
        }
    }
...