swift3 - 如何在不造成 fps 延迟的情况下移动 Sprite

标签 swift3 sprite-kit xcode8

我正在创建一个 spritekit 游戏,而且我对 swift 还很陌生。我想要有两个按钮可以让玩家向右或向左移动。当按下按钮(例如向左按钮)时, Sprite 必须开始向左移动而不停止。当它撞到左墙时,它会改变方向并向右移动到另一堵墙,依此类推......我设法让 Sprite 通过使用更新功能来做到这一点。每次调用它时,它都会检查玩家是否按下了按钮,并相应地移动 Sprite ,但是,它会导致一定程度的 FPS 滞后(FPS 会下降到 50)。

我尝试使用 SKActions(例如 MoveBy 和 MoveTo),但无法重新创建我想要 Sprite 执行的操作。

所以我的问题是:如何使用两个按钮让 Sprite 按照我想要的方式移动,并且不会导致 FPS 滞后。任何帮助,将不胜感激。谢谢

以下是我在更新函数中调用的函数,这些函数有效但导致了滞后。

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

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

最佳答案

试试这个代码:

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

这将使玩家有希望地移动而不会降低帧速率。要在 Sprite 撞到墙壁时改变 Sprite 的方向,您必须检查碰撞。当它撞到墙上时,您可以检查正在应用的是 leftMove 还是 rightMove 操作,然后删除该操作并开始相反的操作。

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

关于swift3 - 如何在不造成 fps 延迟的情况下移动 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341932/

相关文章:

ios - 下载并使用大量头像

ios - Swift 3 上的 NotificationCenter 问题

ios - 如何识别触摸了哪个图像

ios - 如何在 SpriteKit 中获得类似于 peek 或 pop 的 3d touch 应用程序图标触觉反馈

ios - 图片加载不正确

xcode - 使用自定义模板 xcode 8 创建组

iOS swift NSMutableData 没有成员 appendString

ios - 如何在另一个节点中创建一个节点

ios - Sprite 不跟踪计数

swift - 是否有与 Swift 3's ' 数据类型等效的 writeToFile?