Libgdx和Box2d检测两个特定物体的碰撞 [英] Libgdx and Box2d Detect Collision of two specific bodies

查看:174
本文介绍了Libgdx和Box2d检测两个特定物体的碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个物体,两个都是动态的,其中一个我已关闭重力,只想在其他物体撞击它时将其打开.我知道我可以设置自己的联系人侦听器,但仅在两个特定主体接触时才想指定一个动作.

I have two bodies, both dynamic, one of them I have turned off the gravity and only want to turn it on when it is hit by my other body. I know I can set my own contact listener but I want to specify an action only if two specific bodies touch.

任何人都有指导吗?

推荐答案

U可以设置正文的用户数据并像这样使用它

U can set the userdata of the body and use it like that

public class GameColiision implements ContactListener

 {

public GameColiision()
{


}

@Override
public void beginContact(Contact contact) {
    // TODO Auto-generated method stub
    Body a=contact.getFixtureA().getBody();
    Body b=contact.getFixtureB().getBody();
    a.getUserData();
    if(a.getUserData() instanceof Obstacle&&b.getUserData() instanceof Car)
    {

    }
}

@Override
public void endContact(Contact contact) {
    // TODO Auto-generated method stub

}

@Override
public void preSolve(Contact contact, Manifold oldManifold) {
    // TODO Auto-generated method stub

}

@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
    // TODO Auto-generated method stub

}

}

public class Obstacle 
 {

public Body rectangleBody;
public Body triangleBody;
World world;
public static final float WIDTH=10/40f; 
public static final float HEIGHT=10/40f; 


public Obstacle(World world,float x,float y) 
{
    this.world=world;
    initRectangle(x,y);
}


private void initRectangle(float x, float y) 
{
    BodyDef  bodyDef=new BodyDef();
    FixtureDef fixtureDef=new FixtureDef();

    bodyDef.type=BodyType.DynamicBody;
    rectangleBody=world.createBody(bodyDef);

    PolygonShape  polygonShape=new PolygonShape();

    polygonShape.setAsBox(WIDTH,HEIGHT);
    fixtureDef.shape=polygonShape;

    fixtureDef.friction=1f;
    fixtureDef.density = 1f;

    rectangleBody.createFixture(fixtureDef);
    rectangleBody.setTransform(x, y, 0) ;   
    rectangleBody.setAngularDamping(0);

    rectangleBody.setUserData(this);

}

希望这可以解决您的问题

Hope this solves your problem

这篇关于Libgdx和Box2d检测两个特定物体的碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆