Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprite Kit different gravity for different sections

I am building a flappy bird game where half of the level is above water, and the other half is below water.

If your bird is in the air, there is regular gravity and when you tap, an impulse is applied going straight up.

If your bird is in the water, gravity should be in the negative direction (going up) and be less. When you tap, an impulse is applied going straight down.

Can I set a scene's gravity in different places?

I thought of using a timer to apply negative forces if the bird is in the water, but it's all over the place.

Also, I can't just change the entire scene's gravity because there are other SKSprite objects in the scene that should have different gravity applied to them (for instance one bird in the air should be flapping up when tapping, and a bird that dove into the water should be swimming down when tapping all at the same time).

like image 419
Kjell Avatar asked May 23 '26 20:05

Kjell


1 Answers

Gravity is the same throughout the world, so you can't have areas of different gravity.

However, just because SpriteKit doesn't offer a higher level abstraction for something doesn't mean it's difficult to do for yourself. SpriteKit's constant gravity does the same thing to a body as if you apply a force to it with the same magnitude and direction every time your scene's update: method runs.

So, you can do different gravity in the upper and lower parts of your scene in your update: method.

  1. Check the y-coordinate of your bird.
  2. If it's below whatever threshold separates water from air, use applyForce: to apply an upward force. If it's above the water, apply a downward force.
  3. Because this happens every frame, the bird will accelerate downward when above the water and upward when below, and you should see a nice loss of momentum effect just after the transition.

You'll need to tweak the magnitude of your forces until it behaves just right for the gameplay you want. When you do, be aware that the units for applyForce: are 150x those of SKPhysicsWorld's gravity (because of what's probably an Apple bug) and depend on the mass of your physics body (because of Newton's second law).

like image 160
rickster Avatar answered May 30 '26 14:05

rickster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!