Sprite kit SpriteKit-触摸移动,如何防止节点跳到触摸位置
我为touch编写了如下代码:Sprite kit SpriteKit-触摸移动,如何防止节点跳到触摸位置,sprite-kit,Sprite Kit,我为touch编写了如下代码: "override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else {return} let location = touch.location(in: self) player.position = location" “覆
"override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
player.position = location"
“覆盖功能触摸移动(touchs:Set,带有事件:UIEvent?){
guard let touch=touch.first else{return}
让位置=触摸。位置(in:self)
player.position=位置“
问题是节点/播放器将跳转到我在场景中触摸和移动的任何位置。
我该如何解决这个问题?谢谢。我将用伪代码回答这个问题,原因有两个,我在这里帮助您不必为您这样做,作为一个初学者,了解如何自己这样做可能会大有裨益
var ball: SKSpriteNode!
var minWidth: CGFloat = 0
var maxWidth: CGFloat = 0
var startPosX: CGFloat = 0
var startBallPosX: CGFloat = 0
func didMove() {
//did move func of the scene
//setup ball and min and max widths
ball = SKSpriteNode()
addChild(ball)
minWidth = scene.frame.minX
maxWidth = scene.frame.maxY
}
func touchesBegan() {
let location = touch.location(in: self)
startPosX = location.x
startBallPosX = ball.position.x
}
func touchesMoved() {
let location = touch.location(in: self)
var moveXValue = location.x - startPosX
if startBallPosX + moveXValue > maxWidth {
//if ball wants to go past right edge of screen keep it at the edge
ball.position.x = maxWidth
}
else if startBallPosX + moveXValue < minWidth {
//if ball wants to go past left edge of screen keep it at the edge
ball.position.x = minWidth
}
else {
ball.position.x = startBallPosX + moveXValue
}
}
var-ball:SKSpriteNode!
var minWidth:CGFloat=0
var maxWidth:CGFloat=0
var startPosX:CGFloat=0
var startBallPosX:CGFloat=0
func didMove(){
//你把现场的func移走了吗
//设置球和最小和最大宽度
ball=SKSpriteNode()
addChild(球)
minWidth=scene.frame.minX
maxWidth=scene.frame.maxY
}
func touchesbeated(){
让位置=触摸。位置(in:self)
startPosX=location.x
startBallPosX=球的位置.x
}
func touchesMoved(){
让位置=触摸。位置(in:self)
var moveXValue=location.x-startPosX
如果startBallPosX+moveXValue>maxWidth{
//如果球想越过屏幕的右边缘,保持在边缘
ball.position.x=最大宽度
}
否则,如果startBallPosX+moveXValue
您还没有说您想要的输出应该是什么。我希望节点随着我的触摸移动。例如,当前如果我触摸屏幕上的某个位置,节点将跳转到该位置,我不希望这样。我尝试使用一个变量来修复它,但另一个问题是节点可以移出屏幕。因此另一个问题是,无论我在何处触摸或移动节点,如何将其保持在屏幕内。