swift - SpriteKit swift : How to make a sprite jump in place when tapped?

标签 swift sprite-kit skphysicsbody

所以我一直在开发一款游戏,并且有一个正在运行的小 Sprite 。每当用户点击屏幕躲避障碍物时,我都需要让他跳起来。我还需要他跳完后回到地面上的起点。

最佳答案

你可以尝试这样的事情!

import SpriteKit

class GameScene: SKScene {
    var player: SKSpriteNode?

    override func didMove(to view: SKView) {
        player = self.childNode(withName: "player") as? SKSpriteNode
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { self.touchDown(atPoint: t.location(in: self)) }
    }

    func touchDown(atPoint pos: CGPoint) {
        jump()
    }

    func jump() {
        player?.texture = SKTexture(imageNamed: "player_jumping")
        player?.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 500))
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { self.touchUp(atPoint: t.location(in: self)) }
    }

    func touchUp(atPoint pos: CGPoint) {
        player?.texture = SKTexture(imageNamed: "player_standing")
    }

}

在播放器的属性检查器窗口中,确保只选择“动态”和“受重力影响”选项,否则它不会在跳跃后落回地面。:)

我不认为物理学对于一个简单的游戏来说会像以前的回答中有人说的那样过分...对于 iPhone 或 iPad 硬件来说这不是什么大问题,它们具有疯狂的计算能力。

enter image description here

关于swift - SpriteKit swift : How to make a sprite jump in place when tapped?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334473/

相关文章:

swift - 每当我从菜单加载游戏场景时,尺寸就太大了

Swift SKSpriteNode 将消失但仍可点击

xcode - 理解 SpriteKit 节点的概念

swift - 如何在 spritekit 中获取 PhysicsBody SKNode 的方向

swift - 检查单个 Unicode 标量的字符集会产生奇怪的行为

ios - 如何以编程方式为文本添加大纲?

swift - 循环遍历场景中的所有对象/ Sprite