box2d 碰撞检测_Cocos2d Box2D之碰撞检测

|版权声明:本文为博主原创文章,未经博主允许不得转载。

在Box2D中碰撞事件由b2ContactListener类函数实现,b2ContactListener是Box2D提供的抽象类,它的抽象函数:

1 ///Called when two fixtures begin to touch.两个物体开始接触时会响应,但只调用一次。

2 virtual void BeginContact(b2Contact*contact) { B2_NOT_USED(contact); }3

4 ///Called when two fixtures cease to touch.分离时响应。但只调用一次。

5 virtual void EndContact(b2Contact*contact) { B2_NOT_USED(contact); }6

7

8

9 ///This is called after a contact is updated. This allows you to inspect a10 ///contact before it goes to the solver. If you are careful, you can modify the11 ///contact manifold (e.g. disable contact).12 ///A copy of the old manifold is provided so that you can detect changes.13 ///Note: this is called only for awake bodies.14 ///Note: this is called even when the number of contact points is zero.15 ///Note: this is not called for sensors.16 ///Note: if you set the number of contact points to zero, you will not17 ///get an EndContact callback. However, you may get a BeginContact callback18 ///the next step.持续接触时响应,它会被多次调用。

19 virtual void PreSolve(b2Contact* contact, const b2Manifold*oldManifold)20 {21 B2_NOT_USED(contact);22 B2_NOT_USED(oldManifold);23 }24

25 ///This lets you inspect a contact after the solver is finished. This is useful26 ///for inspecting impulses.27 ///Note: the contact manifold does not include time of impact impulses, which can be28 ///arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly29 ///in a separate data structure.30 ///Note: this is only called for contacts that are touching, solid, and awake.31

32 ///持续接触时响应,调用完preSolve后调用。

33 virtual void PostSolve(b2Contact* contact, const b2ContactImpulse*impulse)34 {35 B2_NOT_USED(contact);36 B2_NOT_USED(impulse);37 }

View Code

第一步:我们检测碰撞的类要继承自public b2ContactListener

第二步:创建物理世界的监听对象(在init()中添加)

第三步:在类中添加检测碰撞的函数(上面的四个中选择一个)

第四步:进行碰撞检测

如上:我要检测小鸟是否受到了碰撞,那么我通过contact->GetFixtureA()和contact->GetFixtureB()去取得当前的物理世界中产生碰撞的物体是否等于小鸟的刚体变量(birdBody)。如果相等说明产生了碰撞,如果不相等则说明没有碰撞。

To find out when a fixture collides with another fixture in Box2D, we need to register a contact listener. A contact listener is a C++ object that we give Box2D, and it will call methods on that object to let us know when two objects begin to touch and stop touching. we can’t just store references to the contact points that are sent to the listener, because they are reused by Box2D. So we have to store copies of them instead.

void MyContactListener::BeginContact(b2Contact* contact)

{

// We need to co

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值