gpt4 book ai didi

java - libgdx中box2d检测动态体和静态体碰撞的正确方法

转载 作者:行者123 更新时间:2023-12-02 06:42:18 25 4
gpt4 key购买 nike

这是我使用的一个简单代码,我认为它是有效的,我不知道是否有更好的解决方案。

// 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

}

非常感谢,戴夫

最佳答案

也许你可以看看PeaWorld demo code 。我相信它几乎可以解决同样的问题。

关于java - libgdx中box2d检测动态体和静态体碰撞的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19031112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com