Search code examples
libgdxbox2dcollision

Using box2d to detect collisions, but ignore the forces


I'm using libgdx and box2d to detect collisions, but I want some collision to be detected but the forces not to play out.

Eg, I want to detect when the character collides with a coin but don't want the coin to affect the player's movements.

Is this even possible using box2d? If so, how can I go about doing it?


Solution

  • I'm not sure what you want do, but if I understand what you want to do, you can create a sensor fixture type, this pseudo example:

    FixtureDef fd1 = new FixtureDef();
    //fd1.friction = 0.5f;
    
    PolygonShape pSTest = new PolygonShape();
    
    //size you want for example:
    pSTest.setAsBox(4f / PIXEL_POR_METRO, 
                    1f / PIXEL_POR_METRO, 
                    new Vector2(22f / PIXEL_POR_METRO, -1f / PIXEL_POR_METRO),
                    0f);
    
    fd1.shape = pSTest;
    fd1.isSensor = true;
    
    yourBody.createFixture(fd1).setUserData("yourId");
    

    looks ContactListener interface, for example preSolve

    note that sensor, this is not called for sensors.

    info

    setAsBox(float hx, float hy, Vector2 center, float angle)
    
    Parameters:
    hx the half-width.
    hy the half-height.
    center the center of the box in local coordinates.
    angle the rotation in radians of the box in local coordinates.