我希望相对于玩家的触摸来移动 Sprite 。我熟悉 moveTo SKActions,但是我想知道如何实现 Sprite 移动,其中 Sprite 随着用户的触摸移动而移动。
例如,我在屏幕中央有一个 Sprite 。如果我触摸屏幕底部并向上移动手指, Sprite 将从中心向上移动(它的原始位置)。
谢谢!
最佳答案
试试这个:
import SpriteKit
class GameScene: SKScene {
var node = SKSpriteNode()
var nodePosition = CGPoint()
var startTouch = CGPoint()
override func didMove(to view: SKView) {
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
// node set up
node = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
node.position = CGPoint.zero
self.addChild(node)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let location = touch?.location(in: self){
startTouch = location
nodePosition = node.position
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let location = touch?.location(in: self){
node.run(SKAction.move(to: CGPoint(x: nodePosition.x + location.x - startTouch.x, y: nodePosition.y + location.y - startTouch.y), duration: 0.1))
}
}
}
关于swift - 如何在 spritekit 中通过触摸将 Sprite 相对于其原始位置移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49781837/