我正在尝试检测玩家与传感器主体的碰撞。想象一下平台游戏中的收藏品......我想在玩家与收藏品发生碰撞时运行一个事件。
正如您将从我的代码中看到的那样,我正在将一个动态主体附加到可收集对象以及一个传感器主体,我希望将一个玩家碰撞“事件”附加到玩家与传感器发生碰撞时。似乎有一个“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;
}
}