Mouse-Controlled Movement – Click to Select & Move in LibGdx

In my sixteenth video of the “Building a Game Development Framework” series, I focus on adding background image handling and implementing mouse-controlled movements for game objects.

I introduce a formalized approach to handling game backgrounds via a new Background interface and a FixedBackground implementation.

  • Separation from Collisions: Backgrounds are treated as purely visual elements. They are rendered behind all other objects (such as game pieces), and the system does not test for physical collisions with them.
  • Tiling and Stretching: The FixedBackground can either “stretch” to fill the entire screen or “tile” an image (repeat it) if the original asset is smaller than the display area. I demonstrate this by using a checkerboard pattern.
  • Viewport Syncing: The background logic includes a screenOrigin setting to keep the background fixed relative to the player’s view, even if the game camera moves.

I have updated the core feature with a specialized movement class that lets users move actors with the mouse. In this video, I show how to “pick up” a chip and move it.

  • Selection Logic: The system uses a contains(x, y) check to determine if the user’s mouse click is physically over the actor’s bounding box.
  • Two Interaction Modes:
    • Hold-to-Drag: The actor moves only while the mouse button is held down.
    • Click-to-Toggle: Clicking once “attaches” the actor to the cursor, and clicking a second time “drops” it.
  • Offset Handling: To prevent the actor from “snapping” its top-left corner to the cursor, the movement class calculates the exact offset of where the user clicked relative to the sprite’s center. This ensures the drag feels smooth and natural.

I show how the drag movement interacts with the framework’s existing collision system:

  • Physics Reversion: If you drag a game piece into another object, the framework detects the collision and “reverts” the movement, effectively blocking the drag.
  • The “Overlap” Bug: In early testing, dragging one piece over another would cause the system to accidentally “swap” control to the second piece. I fix this by strictly tracking the “Active” state of the specific actor being dragged, ensuring input isn’t stolen by overlapping sprites.

To support this functionality, I have updated several base classes:

  • SpriteUpdate & BoundingBox: Added the contains(x, y) method to allow actors to sense when they are being hovered or clicked.
  • SimpleScreen: The rendering loop was slightly reorganized to ensure backgrounds are drawn first, followed by actors and UI elements, preventing game objects from being hidden behind the board.

By the end of the video, I demonstrate a functional board game setup where red and black checker pieces can be naturally dragged and dropped onto a tiled game board while obeying physical boundaries.

The Gdx2DGameFramework can be found here on github.