我将InteractiveTileObject类用作Coin类的超类,我设置了worldContactListner类来侦听主体与硬币对象之间的碰撞。下面为worldcontactlistner提供的代码永远不会行进; System.out.println("Im here 2")
(在WorldContactListner类中),我不明白为什么,硬币类是InteractiveTileObject的实例,应执行onCollision方法,请帮助我确定出什么问题。代码如下:
public class Coin extends InteractiveTileObject {
public Coin(World world, TiledMap map, Rectangle rectangle) {
super(world, map, rectangle);
fixture.setUserData(this);
}
@Override
public void onCollision() {
Gdx.app.log("Coin","Collision");
}
}
public abstract class InteractiveTileObject {
protected World world;
protected TiledMap map;
protected TiledMapTile tile;
protected Body body;
public Fixture fixture;
public InteractiveTileObject(World world, TiledMap map, Rectangle rectangle) {
this.world = world;
this.map = map;
BodyDef bodyDef = new BodyDef();
FixtureDef fixtureDef = new FixtureDef();
PolygonShape polygonShape = new PolygonShape();
for (MapObject mapObject : map.getLayers().get(6).getObjects().getByType(RectangleMapObject.class)) {
rectangle = ((RectangleMapObject) mapObject).getRectangle();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set((rectangle.getX() + rectangle.getWidth() / 2) / trollVersusZombies.PPM, (rectangle.getY() + rectangle.getHeight() / 2) / trollVersusZombies.PPM);
body = world.createBody(bodyDef);
polygonShape.setAsBox(rectangle.getWidth() / 2 / trollVersusZombies.PPM, rectangle.getHeight() / 2 / trollVersusZombies.PPM);
fixtureDef.shape = polygonShape;
fixtureDef.isSensor = true;
fixture = body.createFixture(fixtureDef);
}
}
public abstract void onCollision();
}
public class WorldContactListener implements ContactListener {
@Override
public void beginContact(Contact contact) {
Fixture fixA = contact.getFixtureA();
Fixture fixB = contact.getFixtureB();
if( fixA.getUserData() == "body" || fixB.getUserData() == "body")
{
Fixture body = fixA.getUserData().equals("body") ? fixA : fixB;
Fixture object = body == fixA ? fixB : fixA;
System.out.println("Im here"); //Code comes here
if(object.getUserData() instanceof InteractiveTileObject)
{
System.out.println("Im here 2"); //Code doesnt get here
((InteractiveTileObject)object.getUserData()).onCollision();
}
}
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
}