Movement in Games

In this video for “Building a Game Development Framework” series, I focus on integrating LibGDX input handling into my custom 2D framework. The goal is to move away from complex, repeated logic and instead encapsulate movement and input into reusable classes.

First, I handle the coordinate system. A common issue in game development is that mouse input coordinates often start from the top-left, while OpenGL (used by LibGDX) renders from the bottom-left. I created a ScreenInput helper class to:

  • Flip the Y-axis: Automatically subtracts the input Y-position from the screen height so the “game world” Y matches the “input” Y.
  • Delta Movement: Provides methods to get the change in mouse position (DeltaX, DeltaY), which is essential for mechanics like first-person camera rotation or smooth scrolling.

Then I demonstrate the difference between the primary LibGDX input polling methods:

  • isButtonPressed vs. isButtonJustPressed: The former returns true as long as a button is held down (useful for continuous fire), while the latter fires only once per click (useful for menus).
  • Key Input: Similar logic is applied to keyboard keys using Gdx.input.isKeyPressed.
  • Multi-touch: Brief mention of how to handle specific finger indexes for mobile development.
  • Text Input: A quick look at a built-in dialog for simple user text entry.

Then I explain my Movement Interface and its implementations, which decouple “how a character moves” from “how the animation is drawn.”

  • Base Movement & Magnitudes: A base class calculates movement “magnitudes” using sine and cosine. This ensures that when a character moves diagonally, they don’t move faster than they do horizontally or vertically (maintaining a consistent speed).
  • Two-Key Movement: Encapsulates logic for moving along a single axis (e.g., Left/Right or Up/Down) using two specified keys.
  • Four-Key Movement: Handles full 2D movement. It includes a “Multi-key” mode that allows for diagonal movement (8 directions) by checking if two keys (like Up and Right) are pressed simultaneously.

I sum this up by showing how the framework simplifies the code. Instead of writing complex if statements in every character class, a developer only needs about five lines of code to:

  1. Initialize the movement type (e.g., FourKeyMovement).
  2. Update the movement with delta time.
  3. Update the animation’s direction based on the movement’s calculated heading.
  4. Update the character’s X and Y coordinates using the movement’s calculated updates.

This modularity allows for easy swapping of controls—for example, switching a character from keyboard controls to a different input method—without touching the animation logic.