如何在不导致 fps 延迟的情况下移动精灵



我正在创建一个spritekit游戏,我对swift相当陌生。我想要两个按钮,让玩家向右或向左移动。当按下按钮时,比如说左按钮,角色必须开始向左移动而不停止。当它撞到左边的墙时,它会改变方向,向右移动到另一堵墙,依此类推......我设法让精灵通过使用更新功能来做到这一点。每次调用它时,它都会检查玩家是否按下按钮,并相应地移动角色,但是,它会导致一些 FPS 延迟(FPS 会下降到 50(。

我尝试使用像MoveBy和MoveTo这样的SKActions,但无法重新创建我想要精灵做的事情。

所以我的问题是:如何使用两个按钮让精灵按照我想要的方式移动,而不会导致 FPS 延迟。任何帮助将不胜感激。谢谢

以下是我在更新函数中调用的函数,它们有效但会导致滞后。

func moveRight() {
    sprite.xScale = 1
    sprite.position.x += 4
}
func moveLeft() {
    sprite.xScale = -1
    sprite.position.x -= 4
}

试试这段代码:

当按下按钮时,它会永久运行移动操作,当按钮被释放时,它会删除该操作

这将使播放器有望在不降低帧速率的情况下移动。要在角色撞到墙壁时改变它的方向,你必须检查是否有碰撞。当它碰到墙上时,您可以检查正在应用的是左移动还是右移动动作,然后删除该动作并开始相反的动作。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        if(leftButton.contains(location) { // check if left button was pressed
            moveLeft()
        } else if(rightButton.contains(location) { //check if right button was pressed
            moveRight()
        }
    }
}
func moveLeft() {
    //Check if it's already moving left, if it is return out of function
    if((sprite.action(forKey: "leftMove")) != nil) {
        return
    }
    //Check if its moving right, if it is remove the action
    if((sprite.action(forKey: "rightMove")) != nil) {
        sprite.removeAllActions()
    }
    //Create and run the left movement action
    let action = SKAction.move(by: -100, duration: 1)
    sprite.run(SKAction.repeatForever(action), withKey: "leftMove")
}
func moveRight() {
    //Check if it's already moving right, if it is return out of function
    if((sprite.action(forKey: "rightMove")) != nil) {
        return
    }
    //Check if its moving left, if it is remove the action
    if((sprite.action(forKey: "leftMove")) != nil) {
        sprite.removeAllActions()
    }
    //Create and run the right movement action
    let action = SKAction.move(by: 100, duration: 1)
    sprite.run(SKAction.repeatForever(action), withKey: "rightMove")
}

最新更新