我正在嘗試檢測與傳感器主體碰撞的玩家。想象一下在平臺遊戲中的收藏......當玩家與收藏品相撞時,我想運行一個事件。Libdgx Box2D - 檢測碰撞
正如您將從我的代碼中看到的那樣,我將一個動態物體附加到收藏對象以及一個傳感器主體,我希望當玩家與傳感器發生碰撞時,我希望將一個玩家碰撞「事件」附加到傳感器主體上。看起來有一個「ContactListener」接口,但實現這些方法似乎沒有任何作用。我會如何去做這件事?
如果沒有做任何的下方的一個更好的辦法,任何意見,將不勝感激:)
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
public class CoinCollectible extends GameObject{
public CoinCollectible(Vector2 position, float angle){
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.x = position.x;
bodyDef.position.y = position.y;
bodyDef.angle = angle;
PolygonShape poly = new PolygonShape();
poly.setAsBox(1, 1);
FixtureDef itemFixture = new FixtureDef();
itemFixture.shape = poly;
itemFixture.density = 1;
itemFixture.filter.categoryBits = PhysicsLayers.LAYER_ITEM;
itemFixture.filter.maskBits = PhysicsLayers.MASK_PLAYER;
fixtureArray.add(itemFixture);
massData.mass = 1f;
// Attach a collision sensor
FixtureDef sensorFixture = new FixtureDef();
sensorFixture.shape = poly;
sensorFixture.isSensor = true;
sensorFixture.filter.maskBits = PhysicsLayers.LAYER_PLAYER;
fixtureArray.add(sensorFixture);
// Clean up
poly.dispose();
}
}
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.MassData;
import com.badlogic.gdx.physics.box2d.World;
public class GameObject{
public Body body = null;
public BodyDef bodyDef = new BodyDef();
public MassData massData = new MassData();
protected List<FixtureDef> fixtureArray = new ArrayList<FixtureDef>();
public GameObject(){}
public Body addToWorld(World world){
if(bodyDef == null)
return null;
body = world.createBody(bodyDef);
while(fixtureArray.size() > 0){
body.createFixture(fixtureArray.remove(0));
}
body.setMassData(massData);
return body;
}
}
請解釋一下什麼是錯的與OP的代碼,爲什麼這通過編輯你的答案解決了問題*。 – 2014-09-14 16:54:49