我正在向 libgdx 中的 box2d 世界添加带有固定装置的主体。我想检测用户是否触摸(点击)了一个对象。我该怎么做呢?谢谢
问问题
2884 次
2 回答
8
2
用户只有在接触到Fixture
包含在这个身体中的一些 ' 时才会接触到身体。这意味着,您可以检查每个Fixture
使用Body
方法testPoit()
:
public class Player {
private Body _body;
public boolean isPointOnPlayer(float x, float y){
for(Fixture fixture : _body.getFixtureList())
if(fixture.testPoint(x, y)) return true;
return false;
}
}
接下来,您需要InputAdapter
像这样创建:
public class PlayerControl extends InputAdapter {
private final Camera _camera;
private final Player _player;
private final Vector3 _touchPosition;
public PlayerControl(Camera camera, Player player) {
_camera = camera;
_player = player;
// create buffer vector to make garbage collector happy
_touchPosition = new Vector3();
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// don't forget to unproject screen coordinates to game world
_camera.unproject(_touchPosition.set(screenX, screenY, 0F));
if (_player.isPointOnPlayer(_touchPosition.x, _touchPosition.y)) {
// touch on the player body. Do some stuff like player jumping
_player.jump();
return true;
} else
return super.touchDown(screenX, screenY, pointer, button);
}
}
最后一个 - 设置这个处理器来监听用户输入:
public class MyGame extends ApplicationAdapter {
@Override
public void create () {
// prepare player and game camera
Gdx.input.setInputProcessor(new PlayerControl(cam, player));
}
在此处阅读有关触摸处理的更多信息
于 2017-06-07T18:19:21.700 回答