我更改了一个函数中的值,并想访问同一类中另一个函数中的值。我的代码:
class person{
var fieldsWidth = CGFloat()
var xPos = CGFloat()
var yPos = CGFloat()
var player = SKSpriteNode()
func addPlayer(gameScene: GameScene, x: CGFloat, y: CGFloat){
fieldsWidth = gameScene.screenWidth / CGFloat(hintergrund().fieldsX)
player = SKSpriteNode(imageNamed: "player")
player.size = CGSize(width: fieldsWidth, height: fieldsWidth)
player.position = CGPoint(x: x, y: y)
gameScene.addChild(player)
xPos = x
}
func move(gameScene: GameScene, point: CGPoint, fWidth: CGFloat){
print(xPos)
}
和游戏场景:
class GameScene: SKScene {
var screenWidth = CGFloat()
var screenHeight = CGFloat()
var touchLocation = CGFloat()
var fieldsWidth = CGFloat()
let player = person()
override func didMoveToView(view: SKView) {
screenWidth = self.size.width
screenHeight = self.size.height
fieldsWidth = screenWidth / CGFloat(hintergrund().fieldsX)
person().addPlayer(self, x: fieldsWidth/2, y: fieldsWidth/2)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
let touch = touches.first
var point = CGPoint()
point = touch!.locationInNode(self)
player.move(self, point: point, fWidth: fieldsWidth)
}
}
不知何故,xPos 的值只是在 addPlayer 中的本地值。如何正确访问 xPos 的值?希望你能帮助我。
最佳答案
以下代码在 XCode Version 7.1 (7B91b) playground 中完全按照我的预期运行
class person{
var yPos = CGFloat()
func function1(y: CGFloat){
yPos = y
print(yPos) //Value of yPos is 31.25; correct!
}
func function2(){
print(yPos) //Value of yPos is 0.0; wrong!??
}
}
let foo = person()
foo.function1(31.25)
foo.function2() //Outputs 31.25
关于Swift:变量的值是公共(public)的但仍然是本地的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593962/