在我的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对象的位置,但是在尝试将laserLoc设置为时,出现错误“使用未解析的标识符'Laser'”激光定位
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属性似乎没有任何问题。有没有解决的办法?提前致谢!
编辑:
我知道“ Laser”纯粹是在shootLaser()方法中本地的,但同样,有没有办法我可以在update方法中访问其属性?
最佳答案
尝试将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)
}