How to determine if a point crosses a body in libgdx

I am adding bodies with fixtures to the box2d world in libgdx. I want to determine if the user has touched (clicked) an object. How can I do it? thanks

+4
source share
2 answers

You must use the libgdx Stage to detect touch events on the Actors (what do you mean as objects here). Best practice is to map the box2d body to the scene actor, which makes it pretty simple to do such things.

To detect a touch:

Implement the touchDown method of the InputProcessor interface to:

  • You need to convert the screen coordinates to scene coordinates using the stage.toStageCoordiantes (...) method.
  • Use the transformed coordinates to detect a hit on an actor (object) in the scene using stage.hit (x, y).
  • stage.hit (x, y) will return the actor to you if a hit is detected.

Hope this helps.

+7
source

A user only touches a body if it touches some of the Fixture contained in that body. This means that you can test each Fixture Body using the 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; } } 

Then you need to create an InputAdapter as follows:

 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 last - configure this processor to listen for 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 processing here.

+1
source

All Articles