Cocos2D 重力? [英] Cocos2D Gravity?

查看:24
本文介绍了Cocos2D 重力?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我知道 Cocos2D 没有内置任何重力 API,所以我需要手动做一些事情.问题是网络上没有任何教程或示例可以显示这一点.

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!

谢谢!

推荐答案

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

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;
}

每一帧精灵的 y 位置都会减少.这就是简单的方法.为了获得更真实的效果,您需要为每个移动对象设置一个速度矢量,并将重力应用于速度(这也是一个 CGPoint).

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;
}

这会导致速度随着时间的推移在向下的 y 方向上增加.这将使物体向下加速越来越快,它下落"的时间越长.

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".

然而,通过修改速度,您仍然可以改变对象的大致方向.例如,要让角色跳跃,您可以设置 velocity.y = 2.0,它会随着时间的推移受到重力影响而向上移动并再次向下移动.

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.

这篇关于Cocos2D 重力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆