访问在特定方法中声明的SKSpriteNode

时间:2015-07-26 19:00:27

标签: swift timer skspritenode

在我的GameScene类中,我有一个名为shootLaser的方法,它创建一个名为Laser的SKSpriteNode,并将其添加为self的子级。每几秒钟在一个计时器上调用此方法

func shootLaser(){
    var Laser = SKSpriteNode(imageNamed: "LaserDot.png")
    Laser.position = CGPointMake(100, 100)
    Laser.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    Laser.physicsBody?.categoryBitMask = PhysicsCatagory.Laser
    Laser.physicsBody?.contactTestBitMask = PhysicsCatagory.Blade
    Laser.physicsBody?.affectedByGravity = false
    Laser.physicsBody?.dynamic = false
    Laser.physicsBody?.density = 0.5   
    self.addChild(Laser)
}

在每次渲染帧时自动调用的update()方法中,我尝试访问Laser对象的位置,但是我收到错误"使用未解析的标识符' Laser& #39;"当我尝试将laserLoc设置为Laser.position

override func update(currentTime: CFTimeInterval)
{
    /* Called before each frame is rendered */

    // moves every value up an index each frame
    let laserLoc = Laser.position
    if (laserPoints[0] != nil){
        for var index = 9; index >= 1; index--
        {
            laserPoints[index] = laserPoints[index - 1]
        }
        laserPoints[0] = CGPointZero
    }

我似乎在访问外部任何方法声明的SKSpriteNodes属性时遇到任何问题。有没有解决的办法?提前谢谢!

编辑:

我知道"激光"在shootLaser()方法中纯粹是本地的,但同样的,有没有办法在update方法中访问它的属性?

1 个答案:

答案 0 :(得分:1)

尝试在类声明之后而不是在函数中而不是Laser。像这样:

class YourClassName: SKScene {

    var Laser = SKSpriteNode(imageNamed: "LaserDot.png")

另外,请确保删除函数内的Laser声明并编辑该函数。

func shootLaser(){
    var Laser = SKSpriteNode(imageNamed: "LaserDot.png")
    Laser.position = CGPointMake(100, 100)
    Laser.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    Laser.physicsBody?.categoryBitMask = PhysicsCatagory.Laser
    Laser.physicsBody?.contactTestBitMask = PhysicsCatagory.Blade
    Laser.physicsBody?.affectedByGravity = false
    Laser.physicsBody?.dynamic = false
    Laser.physicsBody?.density = 0.5
    self.Laser.removeFromParent()   
    self.addChild(Laser)
}