Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocos2D Gravity?

I am really looking to try to have gravity in my game. I know everyone says use Box2D, but in my case I can't. I need to use Cocos2D for the gravity.

I know Cocos2D does not have any gravity API built in so I need to do something manually. The thing is there is like no tutorials or examples anywhere on the web that show this.

Can anyone show me what they have done or can some explain step by step on how to apply a non-constant gravity (One that gets slightly stronger while falling).

I think this will help a lot of people that are facing the same issue that I am having!

Thanks!

like image 721
SimplyKiwi Avatar asked Dec 16 '22 07:12

SimplyKiwi


1 Answers

Gravity is nothing but a constant velocity applied to the body for every physics step. Have a look at this exemplary update method:

-(void) update:(ccTime)delta
{
   // use a gravity velocity that "feels good" for your app
   const CGPoint gravity = CGPointMake(0, -0.2);

   // update sprite position after applying downward gravity velocity
   CGPoint pos = sprite.position;
   pos.y += gravity.y;
   sprite.position = pos;
}

Every frame the sprite y position will be decreased. That's the simple approach. For a more realistic effect you will want to have a velocity vector for each moving object, and apply gravity to the velocity (which is also a CGPoint).

-(void) update:(ccTime)delta
{
   // use a gravity velocity that "feels good" for your app
   const CGPoint gravity = CGPointMake(0, -0.2);

   // update velocity with gravitational influence
   velocity.y += gravity.y;

   // update sprite position with velocity
   CGPoint pos = sprite.position;
   pos.y += velocity.y;
   sprite.position = pos;
}

This has the effect that velocity, over time, increases in the downward y direction. This will have the object accelerate faster and faster downwards, the longer it is "falling".

Yet by modifying velocity you can still change the general direction of the object. For instance to make the character jump you could set velocity.y = 2.0 and it would move upwards and come back down again due to the effect of gravity applied over time.

This is still a simplified approach but very common in games that don't use a "real" physics engine.

like image 88
LearnCocos2D Avatar answered Jan 03 '23 07:01

LearnCocos2D