redGREENblue
redGREENblue

Reputation: 3126

Touch event on a specific area of a box2d body

I have these box2d bodies. I want to check for touch events on the bodies. To be specific, touch on a certain area of the body. Please see the image below, within the body, how can I check if the user touched on the blue area of the body (upper right corner).

enter image description here

I can get the touch coordinates, convert it to world coordinates and check if they overlap with that of the box, but that will trigger even if the box is touched anywhere inside it.

Upvotes: 0

Views: 563

Answers (2)

Drexel
Drexel

Reputation: 11

Maybe its too late but i will answer your question for who needs help.

You should create a fixture for the body which defines body's edges and attributes. Than you need to add fixtures to the body as sensor. Code sample would be seems like this.

    // create bodydef
    BodyDef bdef = new BodyDef();
    bdef.type = BodyType.DynamicBody;
    bdef.position.set(60 / PPM, 120 / PPM);
    bdef.fixedRotation = true;
    bdef.linearVelocity.set(1f, 0f);

    // create body from bodydef
    Body body = world.createBody(bdef);

    // create box shape for player collision box
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(13 / PPM, 13 / PPM);

    // create fixturedef for player collision box
    FixtureDef fdef = new FixtureDef();
    fdef.shape = shape;
    fdef.density = 1;
    fdef.friction = 0;

    // create player collision box fixture
    body.createFixture(fdef);
    shape.dispose();

    // create box shape SENSOR for player
    shape = new PolygonShape();
    shape.setAsBox(13 / PPM, 3 / PPM, new Vector2(0, -13 / PPM), 0);

    // create fixturedef SENSOR for player 
    fdef.shape = shape;
    fdef.isSensor = true;

    // create player SENSOR fixture
    body.createFixture(fdef).setUserData("SENSOR");;

Have a nice day.

Upvotes: 1

m.antkowicz
m.antkowicz

Reputation: 13571

The Body itself has nothing common with Libgdx Input/Output operations - this is what is important to understand. Libgdx is handling touching and gestures by

Then you cannot bind body instance to the listener however you can do this with whole screen (and then calculate somehow if coordinates are in body bounds - then if yes in which part exactly) or you can do this by creating a Scene2d actor instance.

If I were you I would create an Actor (for example rectangle shape) with size of part of body you want to be "touchable". The actor should has attached ClickListener with method that you want to fire on touch. Then in the actor's act() method I would update actor position due to the body position.

Upvotes: 0

Related Questions