Cocos2D Gravity?

回眸只為那壹抹淺笑 提交于 2019-12-03 20:23:07

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.

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