Unable to detect if a rectangle is touched in libg

2019-09-10 11:58发布

问题:

I have a rectangle with a sprite on it and I have to detect if the touch position lies within the rectangle.

This is my code,

    if (Gdx.input.isTouched())
    {
        int x1 = Gdx.input.getX();
        int y1 = Gdx.input.getY();
        Vector3 inputs = new Vector3(x1, y1, 0);
        gamecam.unproject(inputs);
        Gdx.app.log("x" + inputs.x, "y" + inputs.y);
        Gdx.app.log("rect" + rectangle.x, "rect" + rectangle.y);
        if(rectangle.contains(inputs.x,inputs.y))
        {
            Gdx.app.log("x" + inputs.x, "y" + inputs.y);
            Gdx.app.log("rect" + rectangle, "rect" + rectangle.y);
        }
    } 

Rectangle definition,

    BodyDef bdef = new BodyDef();
    bdef.type = BodyDef.BodyType.StaticBody;
    b2body = screen.getWorld().createBody(bdef);

    rectangle = new Rectangle();
    rectangle.setHeight(55);
    rectangle.setWidth(55);
    PolygonShape head = new PolygonShape();
    rectangle.setX(300);
    rectangle.setY(10);
    bdef.position.set((rectangle.getX() - rectangle.getWidth() / 2) / MyJungleGame.PPM, (rectangle.getY() - rectangle.getHeight() / 2) / MyJungleGame.PPM);
    head.setAsBox(rectangle.getWidth() / 2 / MyJungleGame.PPM, rectangle.getHeight() / 2 / MyJungleGame.PPM);
    FixtureDef fdef = new FixtureDef();
    fdef.shape = head;
    setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);

This is my output,

The small rectangle at the bottom of the screen is the rectangle I created. But, nothing happens when I click it. I checked the coordinates and here is the log,

  x-0.925: y-0.5625
  rect300.0: rect10.0
  x-0.925: y-0.5625
  rect300.0: rect10.0
  x-0.925: y-0.5625

I tried checking the touch using the below method,

        if (inputs.x > sprite.getX() && inputs.x < sprite.getX() + sprite.getWidth())
        {
            if (inputs.y > sprite.getY() && inputs.y < sprite.getY() + sprite.getHeight())
            {
                Gdx.app.log("sprite touched", "");
            }
        }

This too doesn't work. Any idea where I made the mistake ? Please help . Thanks in advance

回答1:

Since you are using Box2D, to detect collisions via the common way is more complicated to new users. However, looking on your code... I would advice taking this coordinates in consideration with PPM of your world :

int x1 = Gdx.input.getX();
int y1 = Gdx.input.getY();
Vector3 inputs = new Vector3(x1, y1, 0);

Also, If you are going to build a collision system with box2d, you should use this : http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/