0

I'm trying to draw a bounding box that follows the mouse and is positioned beneath it but the rectangle doesn't move with it, it moves too fast or too slow and not at the right place.

I've tried getting the mouse coordinates and passing them in to a rectangle, then I draw a rectangle at its position so I can see where it is.

mouseRect is a rectangle drawn at the mouse's position:

mouseRect.set((float)Gdx.input.getX(), (float)Gdx.input.getY(), 32, 32);

This is my render method that is meant to draw a rectangle at mouseRect's position:

shapeRenderer.setProjectionMatrix(cam.combined);
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.BLUE);
shapeRenderer.rect(mouseRect.x, mouseRect.y, mouseRect.width, mouseRect.height);
shapeRenderer.end();

The box does move when the mouse moves but it's far too fast and it's not positioned under the mouse as should be expected (there's a giant offset and seems to be inverted but when I make it negative it still doesn't work).

1 Answers1

0

I think you should read about coordinate systems. The mouse system is y-down and screen dependent, while (if I remember correctly), the camera is y-up, centered, and uses the viewport size.

I would suggest using a Stage with a listener for mouseMoved or touchDragged events, which have stage coordinates. Add an actor drawing a rectangle to the stage. You could then move the actor accordingly. You wouldn't have to handle coordinate system changes.

It could look like this:

Actor rectangleActor = new RectangleActor();
stage.addActor(rectangleActor);
stage.addListener(new InputListener() {
    public boolean mouseMoved(InputEvent event, float x, float y) {
        rectangleActor.setPosition(event.getStageX(), event.getStageY());
        return false;
    }
})

See this answer for how to draw a rectangle in an actor.

Nicolas
  • 6,611
  • 3
  • 29
  • 73