iosswiftsprite-kitgravityskphysicsworld

How to get Constant Velocity for Spritekit Gravity


I am making a Tetris kind of game, where I want my blocks to fall at a constant velocity. I want to achieve it using SpriteKit Physics Words Gravity.

Problem is that gravity is necessarily acceleration and hence block start to move faster as they fall. I know I can turn gravity off and use actions to move the block but I wish to do it with gravity.

Is there a way to make the gravitational force in SpriteKit world a linear constant velocity?


Solution

  • Using the default physics you will not achieve what you are looking for.

    In the definition of Gravity in Spite Kit is clear that is a acceleration, so is no possible to achieve linear speed with it.

    A vector that specifies the gravitational acceleration applied to physics bodies in the physics world.


    But, you can have some workarounds to achieve the behavior you want.

    1. Gravity Acceleration 0, and add speed to the falling object.
    2. Limit the maximum Speed of an Object.
    3. Do you own physics

    I Think the best way to do it, with gravity working as default, is by limiting the maximum speed.

    2 - Limit the maximum Speed

    Consulting this post.

    In didSimulatePhysics(), you can verify the speed of the object, and limit it.

    Like this (Credits to @Andrew, in the original post)

    - (void)didSimulatePhysics {
      if (node.physicsBody.velocity.x < MAX_SPEED_X) {
      node.physicsBody.velocity = CGVectorMake(MAX_SPEED_X, MAX_SPEED_Y);
     }
    }