尽管这是一个包含对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) {}
}
但是,我希望能够将一些碰撞逻辑移动到适当的类中
例如,如果Body
与ConveyorBelt
发生冲突,我希望处理该类中ConveyorBelt
特定的逻辑。
因此,ConveyorBelt
拥有自己的beginContact
,beginContact
,preSolve
和postSolve
方法定义,Rectangle
等相同1} >
最好的方法是什么?
类层次结构..
.
└── 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
答案 0 :(得分:1)
感谢提示@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);
}
}