Swift 如何移动节点?

Swift 如何移动节点?,swift,user-interface,sprite-kit,pan,Swift,User Interface,Sprite Kit,Pan,我正在编写一个类似乒乓球的游戏,使用SpriteKit和Swift 5进行学习。我试着让玩家的桨(一个SKNode矩形)在x坐标系下在屏幕上移动,但是做不到 我尝试过这个简单的解决方案: override func touchesMoved(touch:Set,带有事件:UIEvent?){ 对于t-in-touch{ 让位置=t位置(in:self) playerPaddle.position.x=位置.x } 它工作,但似乎只有在点击(触摸)时划桨才会移动,而不是拖动 我也尝试过使用UIP

我正在编写一个类似乒乓球的游戏,使用SpriteKit和Swift 5进行学习。我试着让玩家的桨(一个SKNode矩形)在x坐标系下在屏幕上移动,但是做不到

我尝试过这个简单的解决方案:

override func touchesMoved(touch:Set,带有事件:UIEvent?){
对于t-in-touch{
让位置=t位置(in:self)
playerPaddle.position.x=位置.x
}
它工作,但似乎只有在点击(触摸)时划桨才会移动,而不是拖动

我也尝试过使用UIPangestureRecognitor,但我真的不知道如何调用它,下面是我从苹果官方开发者的文档中复制的代码,并根据我的情况做了一些修改:

@iAction func装甲件(ugestureRecognitor:UIPangestureRecognitor){
guard gestureRecognizer.view!=nil else{return}
let piece=手势识别器.view!
let translation=gesturecognizer.translation(在:piece.superview中)
如果gestureRecognizer.state==。已开始{
self.initialPos=工件中心
}
否则,如果gestureRecognizer.state!=已更改{
设newPos=CGPoint(x:initialPos.x+translation.x,y:initialPos.y)
工件中心=新位置
}
}

您的
TouchsMoved
解决方案对我有效,因此我认为还有其他问题。无论如何,我可以提供一个替代方案:

我还构建了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))
    }
}
override func touchsbegind(touch:Set,带有事件:UIEvent?){
如果playerPaddle.hasActions(){playerPaddle.removeAllActions()}
接触{
让newX=touch.location(in:self).x
设oldX=playerPaddle.position.x
运行(.moveBy(x:newX-oldX,y:0,持续时间:0.5))
}
}

您的
TouchsMoved
解决方案对我有效,因此我认为还有其他问题。无论如何,我可以提供一个替代方案:

我还构建了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))
    }
}
override func touchsbegind(touch:Set,带有事件:UIEvent?){
如果playerPaddle.hasActions(){playerPaddle.removeAllActions()}
接触{
让newX=touch.location(in:self).x
设oldX=playerPaddle.position.x
运行(.moveBy(x:newX-oldX,y:0,持续时间:0.5))
}
}

我猜playerPaddle是一个空的SKNode。我猜playerPaddle是一个空的SKNode。