【发布时间】:2015-03-04 16:43:03
【问题描述】:
我正在 Libgdx 中开发一个游戏,我正在研究 2D 框中两个物体之间的碰撞检测。我使用“Contact Listener”来检测碰撞,但是当身体碰撞时没有任何反应。
这是我的代码
public Player(World world,float x,float y,float width)
{
this.width=width; //IMP
height=width*2;
BodyDef polygon=new BodyDef();
polygon.type=BodyType.DynamicBody;
polygon.position.set(x,y); //
polygon.fixedRotation=true;
PolygonShape poly =new PolygonShape();
poly.setAsBox(width/2,height/2); //
//fixture defn
polygon.position.set(5,4);
FixtureDef polyfixture=new FixtureDef();
polyfixture.shape=poly;
polyfixture.friction=0.8f; //
polyfixture.restitution=0.1f; //
polyfixture.density=3; //
//creating actual body
polybody=world.createBody(polygon);
polybody.createFixture(polyfixture);
polysprite=new Sprite(new Texture("img/car.jpg"));
polysprite.setSize(2, 3); //size of mario
polysprite.setOrigin(polysprite.getWidth()/2, polysprite.getHeight()/2);
polybody.setUserData(polysprite);
第二个身体
BodyDef polygons=new BodyDef();
polygons.type=BodyType.DynamicBody;
PolygonShape polys=new PolygonShape();
polys.setAsBox(2,2);
FixtureDef polyxfixture=new FixtureDef();
polyxfixture.shape=polys;
polyxfixture.friction=0.8f;
polyxfixture.restitution=0.1f;
polyxfixture.density=3;
polybodys=world.createBody(polygons);
polybodys.createFixture(polyxfixture);
poly.dispose();
}
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
Fixture fixtureA=contact.getFixtureA();
Fixture fixtureB=contact.getFixtureB();
if(fixtureA.getUserData() != null && fixtureA.getUserData().equals("polybody") &&
fixtureB.getUserData() !=null && fixtureB.getUserData().equals("polybodys")){
Gdx.app.log("Contact","1");
System.out.println("its colliding");
}
if(fixtureB.getUserData() !=null && fixtureB.getUserData().equals("polybody") &&
fixtureA.getUserData() !=null && fixtureA.getUserData().equals("polybodys"))
{
System.out.println("its colliding");
}
}
我添加了 world.setContactListener(player);其中“玩家”是上述类的名称。
这是我检测碰撞的代码。当我运行代码并测试身体之间的碰撞时,什么也没有发生。我在控制台中使用“println”语句进行了测试。我不知道这里有什么问题。请帮忙。提前致谢!!
【问题讨论】:
-
当您检查用户数据时 1) 您应该使用 .equals() 进行字符串比较,以及 2) 它们应该都是“多体”而不是“多体”吗?我也看不到您将用户数据设置为“多体”的任何点,因此它无法评估为 True。
-
非常感谢。我只是尝试了一下,因为我不知道如何正确使用 getBody() 和 getUserData()。我应该怎么做才能检测两个物体(Polybody 和 Polyboyds)@Samich 之间的碰撞
-
我回答了一个问题,就像我认为你可以帮助stackoverflow.com/questions/27388199/…
-
@AngelAngel 基本上回复了我要编写的确切代码。这是正确的做法。
-
我已经按照您提供的链接中的代码进行了尝试,但仍然无法正常工作。我添加了 world.setContactListener(player);在我创建世界的地方,其中“玩家”是“玩家”类的实例。请参阅上面的更新代码@AngelAngel
标签: java libgdx box2d collision-detection