精灵落在cocos2d

时间:2011-06-18 19:16:02

标签: xcode cocos2d-iphone box2d

我有2个精灵在水平移动,我需要它们在撞墙时自然地摔倒。 我知道如何以一种简单的方式改变每一帧的位置,但这似乎并不自然,而且可能不是正确的方法。

当考虑到速度和y轴时,有一种方法可以发现碰撞并使它们倒下吗?

我只是找不到用box2d或者花栗鼠来做到这一点的简单方法。

任何方向都会很棒。 感谢名单。

3 个答案:

答案 0 :(得分:2)

首先向您的b2World添加自定义联系人监听器。

public class Main
{
      public function Main()
      {
            //init stuff
            var cc:CustomContactListener = new CustomContactListener();
            world.setContactListener(cc);
      }
}

//then on hit call the hit function on sprite
public class CustomContactListener extends b2ContactListener
{
      //Called when a contact point is added.
      public override function Add(point:b2ContactPoint):void 
      {
            //checks if the first shape is a sprite and second is a wall if true call Hit
            if (point.shape1.GetBody().GetUserData().isSprite && point.shape2.GetBody().GetUserData().isWall)
            {
                 point.shape1.GetBody().GetUserData().Hit();
            }
            else if (point.shape2.GetBody().GetUserData().isSprite && point.shape1.GetBody().GetUserData().isWall)
            {
                 point.shape2.GetBody().GetUserData().Hit();
            }
      }
}


public class Sprite
{
      public var hit:Boolean = false;

      //Set hit to true and start applying realistic downward force
      public function Hit()
      {
           hit = true;
      }

      //Enter frame event that applies force
      public function step(e:Event)
      {
           if (hit)
           {
                 b2Vec2 force = new b2Vec2(0, -9.8);
                 bodyOfSprite.ApplyLinearForce(force);
           }
      }
}

这取决于您将所有具体的用户数据设置为拥有它的类。即雪碧,华尔街。您也可以采用相反的方式,一直施加重力并施加相反的力。然后,当你接触到墙壁时,你会停止施加另一个力,重力就会生效。

或者像@ iforce2d如何放置它只是检查精灵的身体的线性速度是否接近或等于零,因为这表明它已经击中了已停止它的东西,而不仅仅是一堵墙,那么你可以只是设置为真。步进功能将完成剩下的工作。这是有限的,因为它只是需要它减速以触发它不会撞到可能不需要的墙。

答案 1 :(得分:0)

使用任何物理引擎只设置世界上正确的重力(如果是box2D,则为b2World)并设置身体的初始速度。所以它会自然而然地落在

答案 2 :(得分:0)

如果你自己设定速度,你应该让它看起来自然:) 改变速度的垂直部分不是一个好主意 - 只需保留原样:

b2Vec2 vel = body->GetLinearVelocity();
vel.x = ...;
body->SetLinearVelocity( vel );