【问题标题】:SpriteKit Swift: How to make a sprite jump in place when tapped?SpriteKit Swift:点击时如何使精灵跳到位?
【发布时间】:2015-09-01 14:38:19
【问题描述】:

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

【问题讨论】:

    标签: swift sprite-kit skphysicsbody


    【解决方案1】:

    你可以试试这样的!

    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 硬件来说没什么大不了的,它们具有疯狂的计算能力。

    【讨论】:

    • 嗨,这正是我需要的,谢谢。如何测试跳跃是否正在进行?当那个人在空中时,我会避免施加新的冲动。我想到的第一个想法是测试人与地面之间的碰撞。如果发生碰撞,则施加脉冲,否则不施加。这是正确的方法吗?
    【解决方案2】:

    对于这样的游戏来说,使用物理是多余的。甚至 2D 马里奥游戏都没有使用物理,所以我怀疑你会需要它。

    作为一个非常简单的实现,您可以使用SKActions 的序列。

    // move up 20
    let jumpUpAction = SKAction.moveBy(x: 0, y: 20, duration: 0.2)
    // move down 20
    let jumpDownAction = SKAction.moveBy(x: 0, y: -20, duration: 0.2)
    // sequence of move yup then down
    let jumpSequence = SKAction.sequence([jumpUpAction, jumpDownAction])
    
    // make player run sequence
    player.run(jumpSequence)
    

    应该可以。不过,我可能在浏览器中输入了错误的内容。

    您可以调整它以使跳跃看起来更自然。也许在跳跃过程中添加更多步骤,以随着时间的推移改变上升/下降的速度,使其看起来像是在加速。等等……

    【讨论】:

    • 会试试这个,非常感谢!!另外,我会把它放在一个单独的函数中还是 didMoveToView 或 touchesBegan 中?
    • @RaeTucker 嗯,这是一个单跳,所以每次你想让角色跳跃时都需要运行这个。所以我建议把它放在一个从你的触摸开始函数中调用的函数中。
    • 谢谢,但无论何时我运行它,我的精灵都不会移动。
    • 当我将播放器设置为我的精灵的名称时,它一直说“使用未解析的标识符:播放器”:let player = SKSpriteNode(imageNamed "koala_walk01")
    • 您需要将 player 替换为您所称的实际 player Sprite 变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多