这是我使用的一个简单代码,我认为它是有效的,我不知道是否有更好的解决方案。
// this code is in render part of my game world class
public void checkCollision(){
int contacts = world.getContactCount();
if(contacts > 0){
for(Contact contact : world.getContactList()){
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
boolean collideOnce = false;
if(fa.getBody().getType() == BodyType.DynamicBody){
collideOnce = fa.getUserData()==null? true : false;
fa.setUserData("t");
}else if(fb.getBody().getType() == BodyType.DynamicBody){
collideOnce = fb.getUserData()==null? true: false;
fb.setUserData("t");
}
if((fa.getBody().getType() == BodyType.DynamicBody && fb.getBody().getType() == BodyType.StaticBody) || (fb.getBody().getType() == BodyType.DynamicBody && fa.getBody().getType() == BodyType.StaticBody)){
if(collideOnce ){
// play some sound or score or something in your game that would benefit to collision between static and dynamic bodies
}
}
}
}
}
我希望有比上面的代码更好的方法,因为我遍历世界上的所有物体并设置 userData("t") => 在扫荡世界上的尸体时会出现问题。
更新这是我的新碰撞检测器,谢谢您的回答
GameWorld implements ContactListener, ...
... //ommitted many codes just to be clear on the solution
// this code is in render part of my game world class
public void checkCollision(){
if(contacts.isEmpty() ) return;
while(!contacts.isEmpty()){
Contact contact = contacts.pop();
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
if(fa == null || fb == null){ return ;}
boolean collideOnce = false;
if(fa.getBody().getType() == BodyType.DynamicBody){
collideOnce = fa.getUserData()==null? true : false;
fa.setUserData("t");
}else if(fb.getBody().getType() == BodyType.DynamicBody){
collideOnce = fb.getUserData()==null? true: false;
fb.setUserData("t");
}
if((fa.getBody().getType() == BodyType.DynamicBody && fb.getBody().getType() == BodyType.StaticBody) || (fb.getBody().getType() == BodyType.DynamicBody && fa.getBody().getType() == BodyType.StaticBody)){
if( collideOnce ){
SoundManager.play(SoundType.DROP , 0.5f);
}
}
}
}
...
//
private Stack<Contact> contacts = new Stack<Contact>();
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
contacts.push(contact);
}
@Override
public void endContact(Contact contact) {
// TODO Auto-generated method stub
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
// TODO Auto-generated method stub
}
非常感谢,戴夫