1

我对 Box2D 和 cocos2d 很陌生。我正在尝试做一些我认为很简单的事情,但结果却比我预期的要困难,而且我在任何地方都找不到有效的答案。

基本上,我想移动一个 b2body 并用动画将它旋转到某个点。

我可以通过以下方式将其调整到正确的位置和旋转:

targetBody->SetTransform(b2Vec2(10.0f,1.0f),10);

但我不知道如何随着时间的推移在那里对其进行动画处理。我尝试在用于身体的精灵上使用 cocos2d 动画,但这没有任何作用。有任何想法吗?

4

2 回答 2

0

In general, you use Box2D to simulate the physical behavior of objects in relation to each other. The rules of mechanics implemented by Box2D dictate how your cocos2d CCSprites move if you continuously update the translation and rotation of your sprites according to their corresponding Box2d b2Body. You will have some kind of repeatedly invoked tick: method in which you step your Box2d world along in time, and in which you update your sprite positions according to simulation results of Box2d.

This pattern corresponds to b2Bodys of type b2_dynamicBody. Physical laws dictate the motion of the body in this case, and your sprites will follow these simulation results. This is why setting a conflicting position of a sprite by means of a CCAction or even directly will be undone almost instantaneously with the next tick:.

Solution 1: kinematic body type

However, there do exist other modes for a b2Body, and one of these is b2_kinematicBody in which the translation is no longer governed by the world but by the velocities or angular speeds you dictate through setters. So it would be one solution to work with body type b2_kinematicBody as in:

b2BodyDef bdef;
bdef.type = b2_kinematicBody;

With this you would manipulate the velocity and angular speed of a b2Body explicitly. In this case, Box2d is still responsible for moving bodies around, but according the velocities you dictate, and without any force effects of collision or gravity applied to this particular body. Also with this strategy, your CCSprites will follow b2Bodys. Setting conflicting positions for your sprites directly or by applying a CCAction would not make sense for the same reason as described above.

Solution 2: decouple sprites from Box2d

An alternative way to animating sprites would be to fully decouple those sprites from Box2d. In this case, you would simply not have any b2Body that governs the position of the sprite you are going to animate. Now, in this case, only you will dictate the position and rotation of your CCSprite, i.e. directly either through its position property or by applying a CCAction.

于 2013-01-20T01:54:48.313 回答
0

有几种方法可以做到这一点。

您可以在每个时间步使用 SetTransform 来随着时间的推移逐渐更新身体的位置,实际上是自己执行动画。这种方法的缺点是身体是“传送”到新位置而不是移动,所以它没有动量,这意味着如果它在途中碰到任何东西,你可能会得到奇怪的结果。不过,如果您知道它不会撞到任何东西或不需要对碰撞做出反应,那就没问题了。

另一种方法是 SetLinearVelocity 和 SetAngularVelocity 给身体适当的运动。这将使碰撞的结果保持真实,并且您不需要在每个时间步保持更新任何内容。另一方面,您需要检测身体何时到达所需位置,然后将速度设置回零,否则它将继续移动。对于动态物体,您还需要以某种方式抵消重力,方法是将物体的重力比例设置为零,或者通过施加向上的力来平衡重力,或者在移动过程中将物体类型更改为运动学。

于 2013-01-20T03:22:27.100 回答