所以我将这段代码作为场景的一部分:
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
// set the background color
backgroundColor = SKColor.whiteColor()
var Player = SKShapeNode(circleOfRadius: 20)
Player.position = CGPoint(x: size.width/2, y: size.height/2)
Player.name = "player"
Player.fillColor = SKColor.blackColor()
Player.physicsBody = SKPhysicsBody(circleOfRadius: 20)
Player.physicsBody?.dynamic = false
addChild(Player)
}
// touch
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
Player.position = CGPoint(x: size.width*0.2, y: size.height*0.2)
print("you touched")
}
}
我得到一个错误提示
"use of unresolved identifier "Player"
我猜,因为播放器最初是在 didMoveToView 函数中创建的,所以它无法识别 touchesBegan 函数中的“Player”。我该如何解决这个问题?我想做的就是在您触摸屏幕的任何地方时将对象置于该位置。
最佳答案
试试这个
var Player = SKShapeNode(circleOfRadius: 20)
...
override func didMoveToView(view: SKView) {
Player.name = "player"
Player.fillColor = SKColor.blackColor()
Player.physicsBody = SKPhysicsBody(circleOfRadius: 20)
Player.physicsBody?.dynamic = false
addChild(self.Player)
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
self.Player.position = touchLocation.position
}
关于swift - 尝试使用 spritekit 和 swift 更改触摸时的对象位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26739613/