为什么我不能在函数更新中调用函数?

时间:2017-03-06 11:30:20

标签: ios sprite-kit swift3 xcode8

请帮帮我!我试图在更新函数中调用我在GameScene类中声明的函数。但是它不能识别这个函数,我想知道这是否与该类或其他东西有关,因为我想每帧运行该函数(但必须为每个spriteCopy更新,具体取决于它自己的运动)确保精灵副本全部遵循该功能并继续,无限。

提前感谢您的帮助。

这是函数的代码,它在某种程度上起作用:

    func touchUp(atPoint pos : CGPoint) {

    if let spriteCopy = self.sprite?.copy() as! SKShapeNode? {
        spriteCopy.fillColor = UIColor.white
        spriteCopy.position = initialTouch
        spriteCopy.physicsBody?.restitution = 0.5
        spriteCopy.physicsBody?.friction = 0
        spriteCopy.physicsBody?.affectedByGravity = false
        spriteCopy.physicsBody?.linearDamping = 0
        spriteCopy.physicsBody?.angularDamping = 0
        spriteCopy.physicsBody?.angularVelocity = 0
        spriteCopy.physicsBody?.isDynamic = true
        spriteCopy.physicsBody?.categoryBitMask = 1 //active
        spriteCopy.isHidden = false

        touchUp = pos

        xAxisLength = initialTouch.x - touchUp.x
        yAxisLength = initialTouch.y - touchUp.y
        xUnitVector = xAxisLength / distanceBetweenTouch * power * 300
        yUnitVector = yAxisLength / distanceBetweenTouch * power * 300
        spriteCopy.physicsBody?.velocity = CGVector(dx: xUnitVector, dy: yUnitVector)


        func directionRotation() {
            if let body = spriteCopy.physicsBody {
                if (body.velocity.speed() > 0.01) {
                    spriteCopy.zRotation = body.velocity.angle()
                }
            }
        }

        directionRotation() //When I run the function with this line, the spriteCopy 
                            //is spawned initially with the right angle (in the direction 
                            //of movement) but doesn't stay updating the angle


        sprite?.isHidden = true

        self.addChild(spriteCopy)


    }

}

以下是功能更新中无法识别的功能:

override func update(_ currentTime: TimeInterval) {

    directionRotation() //this line has error saying "use of unresolved identifier" 

    // Called before each frame is rendered
}

编辑:我想也许有一种方法可以产生多个spriteCopy而没有“copy()”方法,这些方法在生成后不会限制对spriteCopy属性的访问?虽然记住它们仍然必须是单独的SpriteNodes,以便directionRotation函数可以独立应用于每个(FYI:用户可以产生超过50个精灵节点)

1 个答案:

答案 0 :(得分:6)

您已指定本地功能。您需要从 touchUp 功能实现中移出 directionRotation

func directionRotation() {
    if let body = spriteCopy.physicsBody {
        if (body.velocity.speed() > 0.01) {
            spriteCopy.zRotation = body.velocity.angle()
        }
    }
}
func touchUp(atPoint pos : CGPoint) {

 ...
}

修改

我的意思是你需要这样想:

func directionRotation(node:SKNode) {
    if let body = node.physicsBody {
        if (body.velocity.speed() > 0.01) {
            node.zRotation = body.velocity.angle()
        }
    }
}
override func update(_ currentTime: TimeInterval) {

    for node in self.children
    {
        directionRotation(node) 
    }
}