【问题标题】:SpriteKit sprite not following path correctlySpriteKit 精灵未正确遵循路径
【发布时间】:2019-10-07 13:07:27
【问题描述】:

我目前正在将我的 android 游戏转换为 iOS,并且正在尝试让蝙蝠敌人“突袭”玩家。我在 SpriteKit 中创建了曲线,它看起来 fine,但是蝙蝠似乎没有正确地跟随这条线,它消失了几秒钟,然后尽管运行了一个 action.follow看起来正确绘制的路径。路径附加到跟随玩家的 shapeNode。

代码:

func createPath(){
        //All x values are moved back 1 / 4 of the screens width due to the camera being 1 / 4 of the screens width ahead of the player, and y values are halved due to the player being in the centre of y axis
        path.move(to: CGPoint(x: gameScene.frame.width * 3 / 4, y: gameScene.frame.height / 2)) //top right corner

        path.addCurve(to: CGPoint(x: -(gameScene.frame.width / 3.5), y: gameScene.frame.height / 6), control1: CGPoint(x: gameScene.frame.width / 2,  y: -(gameScene.frame.height / 9)), control2: CGPoint(x: 0, y: -(gameScene.frame.width / 9)))
        //to = off screen
        //control1 3 / 4 across screen, slighly higher than player
        //control2 exactly on player (players node height is screen width / 4.5)

        followLine = SKAction.follow(path, asOffset: true, orientToPath: false, duration: 3)

        viewLine.path = path
        gameScene.addChild(viewLine)
    }

    func update(dt: Double){
        if(GameScene.gV.distanceM == 4 && !run){//DistanceM is just a timer (seconds)
            run = true
            bat.run(followLine)
        }
        if run {
            /*time += dt//timer to reset bats position
            if time > 4 {
                run = false
                time = 0
            }*/
        } else {
            bat.position = CGPoint(x: gameScene.pigeonCam.position.x + gameScene.frame.width / 2, y: gameScene.pigeonCam.position.x + gameScene.frame.height / 2)//keep bat at top right of screen
        }
        viewLine.position = gameScene.pigeon.pigeon.position//get node to follow the player
    }

我最好的猜测是,虽然移动 shapeNode 似乎会移动路径,但实际上并没有移动,如果是这样,我可以通过任何其他方式让这条路径“跟随”玩家

【问题讨论】:

    标签: sprite-kit


    【解决方案1】:

    经过多次尝试和错误,我意识到 asOffset 所指的节点是运行动作的节点,所以我将 bat 放在屏幕的右上角并调整了值,我的最终值如下所示:

            let width = gameScene.frame.width
            let height = gameScene.frame.height
    
            path.move(to: CGPoint(x: 0, y: 0)) //top right corner
            //0, 0
            path.addCurve(to: CGPoint(x: -(width * 1.2), y: -(height / 3.5)), control1: CGPoint(x: -(width / 4),  y: -(height / 1.5)), control2: CGPoint(x: -(width * 3 / 4), y: -(height / 2)))
    

    这使得蝙蝠完美地跟随线条,尽管线条的视觉表现很混乱

    【讨论】: