Cocos2D Gravity?

I really try to have seriousness in my game. I know that everyone says they use Box2D, but in my case I canโ€™t. I need to use Cocos2D for gravity.

I know that Cocos2D does not have a built-in gravity API, so I need to do something manually. The fact is that there are no textbooks or examples on the Internet on the Internet that show this.

Can someone show me what they did, or can explain step by step how to apply heavy inconsistent gravity (which gets a little stronger when falling).

I think this will help many people who are facing the same problem as mine!

Thanks!

+4
source share
1 answer

Gravity is nothing more than a constant velocity applied to the body for each step of physics. Take a look at this sample 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; } 

In each frame, the position of the sprite y will be reduced. This is a simple approach. For a more realistic effect, you will need a velocity vector for each moving object and apply gravity to the velocity (which is also 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 leads to the fact that the speed, with time, increases in the downward direction y. This will accelerate and accelerate the object faster, the longer it "falls".

However, by changing the speed, you can still change the general direction of the object. For example, to make a character jump, you can set velocity.y = 2.0 , and it will move up and down again due to the gravity effect applied over time.

This is still a simplified approach, but very common in games that do not use the โ€œrealโ€ physics engine.

+12
source

Source: https://habr.com/ru/post/1381234/


All Articles