我实现了一个带有附加属性的类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'
        }
    }
}

最佳答案

方法enumerateChildNodes 返回SKNode列表

您必须尝试将对象强制转换为类 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)
            }
        }
    }

关于ios - 寻找每帧更新实例属性的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60632490/

10-14 00:43