Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a point intersect body in libgdx

Tags:

java

libgdx

box2d

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

like image 678
dewijones92 Avatar asked Aug 22 '12 10:08

dewijones92


2 Answers

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:

  • You have to transform your screen coordinates to stage coordinates using stage.toStageCoordiantes(...) method.
  • Use the transformed coordinates to detect hit on the Actor (Object) on stage using stage.hit(x, y).
  • stage.hit(x, y) will return you the actor if a hit is detected.

Hope that helps.

like image 175
Rafay Avatar answered Nov 07 '22 18:11

Rafay


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

like image 44
Sergey Bubenshchikov Avatar answered Nov 07 '22 20:11

Sergey Bubenshchikov