Cocos2D Gravity?

只谈情不闲聊 提交于 2019-12-05 02:22:22

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/8130808/cocos2d-gravity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!