即使这是一个包含对JBox2d的引用的问题,它实际上更像是一个普通的Java问题。
使用JBox2d使用Java开发游戏。 JBox2d提供了一个名为ContactListener的回调类。
当身体在我的世界中碰撞时,以下代码片段可以正常工作,我看到Contact begin.已记录到控制台。

// set callback on box2d world
world.setContactListener(new CollisionListener());

// inside game loop, step through physics simulation
world.step(1/60f,  8,  1);

// custom 'ContactListener' definition
public class CollisionListener implements ContactListener{
    private Logger log;

    public CollisionListener(){
        this.log = Logger.getLogger(CollisionListener.class.getName());
        log.info("Registered custom ContactListener");
    }

    public void beginContact(Contact contact) {
    log.info("Contact begin.");
    }
    public void beginContact(Contact contact) {}
    public void preSolve(Contact contact, Manifold oldManifold) {}
    public void postSolve(Contact contact, ContactImpulse impulse) {}
}


但是,我希望能够将一些碰撞逻辑移到适当的类中。
例如,如果BodyConveyorBelt冲突,我想处理该类中特定于ConveyorBelt的逻辑。
因此ConveyorBelt具有自己的beginContactbeginContactpreSolvepostSolve方法定义,与Rectangle相同
什么是实现这一目标的最佳方法?

类层次结构

.
└── InteractiveShape // Parent class, contains 'x, y' position. Many diff classes inherit from it, so i'd like to not have to change this class.
    ├── Circle // sub-class of InteractiveShape
    └── Rectangle // sub-class of InteractiveShape
        └── ConveyorBelt // sub-class of Rectangle

最佳答案

感谢提示@MightyPork,最后使用它..

public void preSolve(Contact contact, Manifold oldManifold) {

    if (contact.getFixtureA().getBody().getUserData() instanceof ConveyorBelt){
        ConveyorBelt conveyorBelt = (ConveyorBelt) contact.getFixtureA().getBody().getUserData();
        conveyorBelt.preSolve(contact, oldManifold);

    }else if (contact.getFixtureB().getBody().getUserData() instanceof ConveyorBelt){
        ConveyorBelt conveyorBelt = (ConveyorBelt) contact.getFixtureB().getBody().getUserData();
        conveyorBelt.preSolve(contact, oldManifold);
    }
}

09-28 08:53