简体   繁体   English

在Box2d和libgdx(android)中检测两个物体之间的碰撞

[英]Detect collision between two bodies in Box2d and libgdx(android)

I am new to libgdx and Box2d engine and I'm developing a game using same .I want to detect collision between two bodies to perform some function.But I'm not aware about the optimum way to do that and also want get point of collision.Kindly provide some suggestion with code.I have already implemented ContactListener but to no avail. 我是libgdx和Box2d引擎的新手,我正在使用同一个引擎开发游戏。我想检测两个物体之间的碰撞以执行某些功能。但是我不知道执行此操作的最佳方法,也想了解一点冲突。请提供一些建议。我已经实现了ContactListener,但无济于事。

I'm using this code as a reference. 我正在使用代码作为参考。

Thanks 谢谢

You already did it the right way to create and set a ContactListener... (for a general setup, the libgdx wiki is great: https://github.com/libgdx/libgdx/wiki/box2d#contact-listeners ) 您已经以正确的方式创建和设置了一个ContactListener ...(对于常规设置,libgdx Wiki很棒: https//github.com/libgdx/libgdx/wiki/box2d#contact-listeners

If you now want to handle the specific contacts, you for exmaple need to add some implementation in the beginContact(); 如果现在要处理特定的联系人,例如,您需要在beginContact();添加一些实现beginContact(); method of your listener. 听众的方法。 The beginContact(); beginContact(); method contains a Contact instance, which holds all you need: 方法包含一个Contact实例,其中包含您所需的全部:

  • FixtureA - the first fixture of a contact 夹具A-触点的第一个夹具
  • FixtureB - the fixture, which FixtureA has collided with FixtureB-FixtureA与之碰撞的灯具
  • WorldManifold - an object that holds the collision points etc WorldManifold-包含碰撞点等的对象

Through the fixtures you can access the bodies and the actors which you are drawing. 通过固定装置,您可以访问要绘制的实体和演员。 The connection to your Actor can be done through the body.setUserData(actor); 可以通过body.setUserData(actor);与Actor建立连接body.setUserData(actor); method. 方法。

Now you need to decide on how to find out the correct collisions. 现在,您需要决定如何找出正确的碰撞。 You can either work with sensors, which are box2d fixtures that just act as a sensor. 您可以使用传感器,它们是仅作为传感器的box2d固定装置。 That means that when an object collides with a sensor, it won't bounce, but fall through it instead. 这意味着,当一个物体与传感器碰撞时,它不会反弹,而会掉落。 But you then are able to detect this contact within the listener. 但是您便可以在侦听器中检测到此联系。

Also, it might be a good idea to add some kind of GameObjectType to your actors. 同样,向您的角色添加某种GameObjectType可能是一个好主意。 Imagine you create a jumping game where the player jumps from platform to platform with water below. 假设您创建了一个跳跃游戏,玩家在有水的情况下从一个平台跳到另一个平台。 Then you would create your actors with types like PLAYER, WATER, PLATFORM ... through the getUserData() method of the box2d bodies yu can now access the Actors and compare their types. 然后,您可以通过box2d实体的getUserData()方法创建具有诸如PLAYER,WATER,PLATFORM等类型的actor,现在yu可以访问Actor并比较其类型。

Eg when an Actor of type PLAYER collides with one of type WATER, he will drown... 例如,当PLAYER类型的演员与WATER类型之一碰撞时,他会溺水而死...

Hope it helps... 希望能帮助到你...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM