微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpriteKit-触摸已移动,如何防止节点跳到触摸位置

如何解决SpriteKit-触摸已移动,如何防止节点跳到触摸位置

我为触摸而编写了如下代码

"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"

问题是节点/播放器将跳到我触摸并移动到场景中的任何位置。 我该如何解决?谢谢。

解决方法

出于两个原因,我将用伪代码回答这个问题,我在这里是为了帮助您不要为您做这件事,并且作为初学者,自己弄清楚如何做到这一点可能会非常有益。

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
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。