Reputation: 1359
I am adding bodies with fixtures to a box2d world in libgdx. I want to detect if the user has touched (clicked) an object. How do I do this? thanks
Upvotes: 5
Views: 3119
Reputation: 5371
User touches the body only if he touches some of Fixture
's contained into this body. This mean, you can check every Fixture
of Body
using testPoit()
method:
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;
}
}
Next, you need to create InputAdapter
like this:
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);
}
}
And the last one - setup this processor to listen user input:
public class MyGame extends ApplicationAdapter {
@Override
public void create () {
// prepare player and game camera
Gdx.input.setInputProcessor(new PlayerControl(cam, player));
}
Read more about touch handling here
Upvotes: 2
Reputation: 6188
You should use libgdx Stage in order to detect touch events on Actors (what you are referring to them as Objects here). The best practice is to map a box2d body to a stage actor which makes it quite simple to do things like that.
To detect touch:
Implement touchDown method of the InputProcessor interface such that:
Hope that helps.
Upvotes: 8