How to make a sprite jump to a specific height with SpriteKit?

后端 未结 2 1939
时光取名叫无心
时光取名叫无心 2020-12-31 20:00

I am trying to use applyImpulse to make a sprite jump to a specific height. In the example code below, the dynamic black circle jumps to the same height as the static red ci

相关标签:
2条回答
  • 2020-12-31 20:42

    Instead of applyImpulse use velocity. Velocity will be more specific. jumpingCircle.physicsBody?.velocity = CGVectorMake(jumpingCircle.physicsBody.velocity.dx, 300.0f); Code not tested.

    0 讨论(0)
  • Figured it out.

    SpriteKit apparently has an undocumented pixel-to-"meter" ratio of 150.

    I discovered this when I realized the mass SpriteKit was automatically calculating for my circles was not 50*pi*r^2 as it should be. I worked backward from mass to calculate the radius SpriteKit was using, and it was 7500, which happens to be 50*150.

    And 12.3? It just happens to be (approximately) the square root of 150.

    So to make these physics simulations work, you have to consider this ratio. I'm calling it "pixel to unit" (PTU) because it has nothing to do with meters in spite of Apple's insistence that SpriteKit uses SI units. But because it's undocumented it seems possible to change, so I'm kicking off my simulation using the following line of code to determine the true PTU:

    let ptu = 1.0 / sqrt(SKPhysicsBody(rectangleOfSize: CGSize(width:1,height:1)).mass)
    

    This is an expensive operation, so it should only be called once. I'm calling it when setting up the initial Scene.

    My impulse calculation is now as follows:

    let dy = mass * sqrt(2 
        * -self.physicsWorld.gravity.dy 
        * (fixedCircle.position.y-jumpingCircle.position.y 
        * ptu))
    

    And now the black circle jumps to perfect alignment with the red circle and I can go back to sleeping at night.

    0 讨论(0)
提交回复
热议问题