Cocos2D重力?

Sim*_*iwi 4 gravity cocos2d-iphone ios

我真的想在我的游戏中尝试引力.我知道每个人都说使用Box2D,但在我的情况下我不能.需要使用Cocos2D来引力.

我知道Cocos2D没有内置任何重力API,因此我需要手动执行某些操作.事情就是在网络上没有任何教程或示例显示这一点.

任何人都可以告诉我他们做了什么,或者可以一步一步地解释如何应用非恒定的重力(一个在下降时稍微强一些).

我认为这将有助于许多面临同样问题的人!

谢谢!

Lea*_*s2D 12

重力只不过是每个物理步骤都应用于身体的恒定速度.看看这个示例更新方法:

-(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;
}
Run Code Online (Sandbox Code Playgroud)

精灵y位置的每一帧都将减少.这是一个简单的方法.为了获得更逼真的效果,您需要为每个移动物体设置速度矢量,并将重力应用于速度(也是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;
}
Run Code Online (Sandbox Code Playgroud)

这具有随着时间的推移速度沿向下y方向增加的效果.这将使物体向下加速越来越快,"下降"的时间越长.

然而,通过修改速度,您仍然可以更改对象的大致方向.例如,为了使角色跳跃你可以设置velocity.y = 2.0并且它将向上移动并且由于随着时间的推移施加重力的影响而再次向下移动.

这仍然是一种简化的方法,但在不使用"真实"物理引擎的游戏中非常常见.