我正在使用SpriteKit和Swift 5编写一个类似乒乓球的游戏,用于学习目的。我试图让玩家的球拍(一个SKNode矩形)在x坐标下在屏幕上移动,但做不到。
我尝试过这个简单的解决方案:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
let location = t.location(in: self)
playerPaddle.position.x = location.x
}它可以工作,但似乎只有在点击(触摸)时才会移动,而不是拖动。
我也试过使用UIPanGestureRecognizer,但我真的不知道如何调用它,下面是我从苹果官方开发者文档中复制的代码,并根据我的情况做了一些修改:
@IBAction func panPiece(_ gestureRecognizer : UIPanGestureRecognizer) {
guard gestureRecognizer.view != nil else {return}
let piece = gestureRecognizer.view!
let translation = gestureRecognizer.translation(in: piece.superview)
if gestureRecognizer.state == .began {
self.initialPos = piece.center
}
else if gestureRecognizer.state != .changed {
let newPos = CGPoint(x: initialPos.x + translation.x, y: initialPos.y)
piece.center = newPos
}
}发布于 2019-08-07 03:53:02
您的touchesMoved解决方案适用于我,所以我认为还有什么地方不对劲。无论如何,我可以提供一个替代方案:
我还构建了Pong来学习Swift和SpriteKit,并且我使用SKActions实现了划板运动。任何时候触摸开始,取消划板的当前动作,并开始移动到新的x位置。
如果你想保持开始的简单性,那么你可以有一个恒定的移动时间,比如0.5秒。否则,您可以通过获取手柄和触摸位置之间的绝对距离并除以某个常量来计算移动时间。更改常量将更改划桨的移动速度。
下面是一个使用常量移动时间的示例:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if playerPaddle.hasActions() { playerPaddle.removeAllActions() }
for touch in touches {
let newX = touch.location(in: self).x
let oldX = playerPaddle.position.x
playerPaddle.run(.moveBy(x: newX - oldX, y: 0, duration: 0.5))
}
}https://stackoverflow.com/questions/57340387
复制相似问题