简体   繁体   English

使用Sprite Kit和Swift跳跃

[英]Jumping with Sprite Kit and Swift

I am creating an app in Sprite Kit and Swift and want to create a sprite that jumps upwards while the screen is pressed, therefore jumping higher as the screen is pressed higher. 我正在Sprite Kit和Swift中创建一个应用程序,并希望创建一个Sprite在按下屏幕时会向上跳,因此在将屏幕按下得更高时会跳得更高。 I have achieved that effect, but gravity in the physics engine is not being applied until after the screen is released. 我已经达到了那种效果,但是直到释放屏幕之后,物理引擎中的重力才被应用。 Therefore the jumps are infinite (increasing exponentially) rather than levelling off at a certain point (like a quadratic equation / parabola). 因此,跳跃是无限的(呈指数增长),而不是在某个点处趋于平稳(如二次方程/抛物线)。

How does one apply gravity actively during the motion of a sprite? 在精灵运动期间如何主动施加重力?

Here is my basic movement code: 这是我的基本运动代码:

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    // touched is true while screen is touched
    if touched {
        nodeLeft.physicsBody?.applyImpulse(CGVector(dx: -5, dy: 0))
    }
 }

NOTE: The object is jumping right and left rather than up and down 注意:对象正在向左和向右跳跃,而不是向上和向下跳跃

The gravity should be working constantly, and probably is. 引力应该不断地工作,也许是。 As you apply an impulse on every tick however, this force is much stronger than the gravity. 但是,当您在每个刻度上施加脉冲时,此力比重力要大得多。

What you need to do is to decrease the effect of the impulse over time. 您需要做的是随着时间的流逝减少脉冲的影响。 This can be achieved in a number of ways, for instance by using the position of the sprite as a base for the impulse: The higher the sprite position, the lower the impulse. 这可以通过多种方式来实现,例如,通过将子画面的位置用作脉冲的基础:子画面的位置越高,脉冲越小。

if touched {
    let minX: CGFloat = 200 // some suitable value
    let multiplier: CGFloat = 10
    let force = max(0, (nodeLeft.position.x / minX - 1) * multiplier)
    nodeLeft.physicsBody?.applyImpulse(CGVector(dx: -force, dy: 0))
}

The minX value in the above example probably makes no sense. 上面示例中的minX值可能没有任何意义。 But the logic is fairly sound I believe. 但是我相信逻辑是合理的。 You obviously need to experiment and tweak this (and the multiplier) to suit your needs. 显然,您需要尝试并调整此(和乘数)以适合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM