Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A reliable 2D enemy is not just a sprite that moves toward the player. Build it as three cooperating layers: sensing gathers facts about the player and level, decision-making selects a behavior, and movement and execution carry it out while respecting collision and combat rules. For a first Java game, a finite-state machine (FSM) with direct movement is a practical foundation; add pathfinding when walls make direct pursuit fail.

This guide uses Java with libGDX as its working context. The example guard patrols waypoints, detects the player, chases and attacks, searches the player’s last known position after losing sight, then returns to its route. These behaviors use deterministic rules—not machine learning—and can be tuned to make an enemy readable and fair.

How enemy AI fits together

Keep the game logic separate from drawing. An enemy update should gather or read sensor data, make a state decision, request movement or an attack, then let collision and combat systems resolve the result. Rendering displays the outcome; it should not decide whether the enemy attacks.

  • Sensing: distance, field of view, line of sight, health, collision state, and path availability.
  • Decision-making: patrol, chase, attack, search, return, stun, or die.
  • Movement and execution: choose a route or steering request, resolve collisions, update animation, and apply damage at the correct time.

A single Enemy class is fine for a first prototype. As behavior grows, split it into components such as EnemySensors, EnemyController, EnemyMotor, EnemyCombat, and an optional pathfinder or animation controller. This separation makes transitions and movement easier to test.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

For example, keep the game loop simple:

public void render() {
    float delta = Gdx.graphics.getDeltaTime();
    enemy.update(player, delta);
    enemy.draw(batch);
}

libGDX’s simple-game tutorial demonstrates delta-time-based movement so speed does not depend on frame rate. The framework’s official site describes support for 2D and 3D games across desktop, Android, browser, iOS, and other targets.

Set up a Java and libGDX project

The official libGDX setup guide currently lists JDK 17 or 21 for its IntelliJ IDEA and Eclipse workflows. Generate a Gradle project with the official setup tool or current project generator, and start with Core and Desktop modules for a first prototype. Use Android Studio if Android is a target; IDE support and platform workflows differ, so check the current setup guide before choosing a mobile toolchain.

  1. Install JDK 17 or 21 and an IDE supported by the target platforms you need.
  2. Generate a libGDX project with Core and Desktop modules.
  3. Create a small top-down map with a player, one enemy, and a few solid walls.
  4. Implement position updates and collision before adding complex AI.
  5. Add one behavior at a time and visualize its state, sensing, and route.

libGDX is the framework, not a built-in enemy-AI system. Its separate gdx-ai extension has its own version lifecycle; do not assume its version number matches libGDX. Check the extension’s current repository or release metadata before adding a dependency.

Model the enemy and its states

Store the enemy’s position, velocity, facing, health, movement speeds, current state, patrol route, timers, and last known player position. Keep related values together so sensing and transitions do not become scattered through rendering code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
public enum EnemyState {
    PATROL, CHASE, ATTACK, SEARCH, RETURN, STUNNED, DEAD
}

Use a consistent transition priority: dead or disabled first, then stun or other interruption, then an immediate attack opportunity, visible target, remembered search target, and finally patrol or return. That order prevents a dead enemy from entering chase because the player happens to be nearby.

An FSM is a good fit when behaviors are mutually exclusive and transitions are easy to describe. Make transitions explicit—for example, “player visible and within range” moves patrol to chase—instead of hiding them in movement code. A small controller can begin with a switch; when each state accumulates its own timers and entry actions, use a state interface with enter, update, and exit methods.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
public void update(Enemy enemy, Player player, float delta) {
    switch (state) {
        case PATROL -> updatePatrol(enemy, player, delta);
        case CHASE  -> updateChase(enemy, player, delta);
        case ATTACK -> updateAttack(enemy, player, delta);
        case SEARCH -> updateSearch(enemy, player, delta);
        case RETURN -> updateReturn(enemy, delta);
        case STUNNED -> enemy.stop();
        case DEAD -> enemy.stop();
    }
}

Move with delta time and collision authority

Express speed in world units per second, then multiply velocity by elapsed seconds. Direct movement toward a target can be written with reusable vectors:

private final Vector2 direction = new Vector2();
private final Vector2 velocity = new Vector2();

public void moveToward(Vector2 target, float speed, float delta) {
    direction.set(target).sub(position);
    if (direction.isZero(0.001f)) {
        velocity.setZero();
        return;
    }
    direction.nor();
    velocity.set(direction).scl(speed);
    position.mulAdd(velocity, delta);
}

After a breakpoint, window switch, or stall, an unusually large delta can move an enemy too far in one update. A simple cap for non-physics movement is float safeDelta = Math.min(delta, 0.05f);; a physics-heavy game should use the engine’s fixed-step simulation instead of moving physics bodies directly with unrestricted render delta.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

AI should request motion; the collision system should decide the legal final position. Use one authoritative position for both the collision body and rendering. Directly moving a sprite while leaving its body behind—or changing a physics body’s transform as if it were an ordinary vector—can cause jitter, tunneling, or desynchronization.

Detect the player without making the enemy omniscient

Check range efficiently

Use squared distance when only comparing against a radius, avoiding a square root:

boolean withinRange(Vector2 enemy, Vector2 player, float range) {
    return enemy.dst2(player) <= range * range;
}

Add facing and line of sight

A directional enemy can test whether the player falls inside its view cone with a dot product. Normalize the direction to the player first; a threshold near 0.5 corresponds roughly to a 120-degree cone, but treat the threshold as a tuning value, not a universal angle.

Vector2 toPlayer = new Vector2(playerPosition).sub(enemyPosition).nor();
boolean insideViewCone = facing.dot(toPlayer) >= 0.5f;

Range and facing alone do not prevent an enemy from detecting someone through a wall. For a tile map, traverse the cells between enemy and player and test whether any blocks vision. With a physics world, raycast between them and inspect the hit. The exact visibility rule depends on whether the game’s walls, doors, foliage, or other objects are opaque.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Remember only the last known position

When sight is lost, store the player’s last visible position and let the enemy investigate it. Do not keep steering toward the player’s live coordinates after the player disappears behind a wall; that makes the enemy behave as if it has perfect information.

if (sensors.canSeePlayer()) {
    lastKnownPlayerPosition.set(player.getPosition());
    timeSinceSeen = 0f;
} else {
    timeSinceSeen += delta;
}

Implement the patrol, chase, search, and return loop

Patrol between waypoints

A patrol route can use fixed world-coordinate points, a loop of tile coordinates, a platform path, or a graph of navigation points. Move toward the current waypoint and switch when inside an arrival radius. Exact-position checks often cause oscillation or overshoot.

Vector2 waypoint = patrolPoints.get(waypointIndex);
enemy.moveToward(waypoint, patrolSpeed, delta);

if (enemy.getPosition().dst2(waypoint) < arrivalRadius * arrivalRadius) {
    waypointIndex = (waypointIndex + 1) % patrolPoints.size();
}

For a polished route, decide whether the enemy pauses at each point, faces along its direction of travel, reverses at endpoints, and what it does if a waypoint becomes blocked. If the enemy is pushed or collision resolution prevents it from reaching a point, detect lack of progress and select a safe recovery behavior rather than waiting forever.

Chase directly in open spaces

In an unobstructed arena, direct pursuit is a suitable first implementation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
enemy.moveToward(player.getPosition(), chaseSpeed, delta);

It is not navigation. In a maze, direct pursuit can push an enemy into a wall, cut through barriers, oscillate near the target, or fail at a platform edge. Separate global route selection from local movement and collision handling when obstacles matter.

Search, then return

When sight is lost, transition to SEARCH, move toward the stored last-known position, and look for the player again. Give the search a timer and a defined completion condition, such as arriving at the location and waiting briefly. If the player is not found before the timer expires, enter RETURN and navigate to the patrol route; on arrival, resume PATROL. These rules make loss of sight meaningful and keep enemies from pursuing indefinitely.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Add pathfinding when the level requires it

Choose navigation based on level shape and enemy movement, rather than adding A* by default.

Situation Initial choice Why or next step
Open arena or freely flying enemy Direct seek Simple and readable; add steering if local motion needs smoothing.
Top-down maze or tile map Grid A* Finds a route around blocked cells; cache the route and follow its next node.
Large spaces with sparse valid routes Navigation graph Hand-authored nodes and links avoid an unnecessarily dense grid.
Many enemies moving toward one target Shared route or flow field Reduces repeated searches for the same destination.
Platformer Platform navigation graph Encode walk, jump, climb, drop, and fall links; ordinary tile A* does not establish jump reachability.

A* on a grid needs walkability, a cost from the start (g), a goal estimate (h), total score (f = g + h), and parent links for reconstructing the route. Manhattan distance is appropriate for four-direction movement; diagonal movement needs an appropriate diagonal or octile heuristic. If diagonal steps are allowed, prevent corner cutting through two blocked neighboring cells unless the game explicitly permits it. Add terrain cost when some walkable cells are slower or more dangerous.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not search every frame for every enemy. Keep the current path and request another when the target has moved far enough, the next route segment is blocked, the enemy reaches a waypoint, the map changes, or a repath timer expires. Handle an empty result explicitly: stop, choose search or return, or select another fallback. The gdx-ai pathfinding API and its pathfinding overview describe graph-based paths and both non-interruptible and interruptible searches that can be spread across frames.

Platformers need more than a grid route: gravity, jump arcs, ledges, one-way platforms, ladders, horizontal acceleration, and hazards affect reachability. A navigation graph should encode actions such as jumping between platforms; links can be precomputed or validated with movement simulation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use steering for local movement, not as a route planner

Steering behaviors can make motion less abrupt once a route or target has been chosen. Seek moves toward a target; arrive slows near it; flee moves away; wander adds variation; separation or collision avoidance helps agents avoid crowding. A useful arrangement is: follow an A* path to its next waypoint, apply seek or arrive locally, then resolve collisions.

Steering is a movement request, not a guarantee of a valid path through a maze or a substitute for collision resolution. The gdx-ai steering documentation covers behaviors such as seek, arrive, collision avoidance, and priority steering. Add them when a direct route is already available and local motion needs improvement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Make attacks timed events

Separate the decision to attack from the animation, damage window, hit detection, cooldown, and recovery. Start an attack only when the player is in range and the cooldown has expired; apply damage once during a defined active window rather than on every update while hitboxes overlap.

public final class EnemyCombat {
    private float cooldown;
    private float attackTimer;
    private boolean hitApplied;

    public void update(float delta) {
        cooldown = Math.max(0f, cooldown - delta);
        if (attackTimer <= 0f) return;

        attackTimer -= delta;
        if (!hitApplied && attackTimer <= 0.15f) {
            hitApplied = true;
            performHit();
        }
        if (attackTimer <= 0f) {
            finishAttack();
        }
    }

    public boolean canStartAttack() {
        return cooldown <= 0f && attackTimer <= 0f;
    }

    public void startAttack() {
        if (!canStartAttack()) return;
        attackTimer = 0.45f;
        cooldown = 1.0f;
        hitApplied = false;
    }
}

Those timings are example values to tune for your game, not a recommended balance. Decide what happens if the player moves out of range during wind-up, the enemy dies or is stunned mid-attack, the player is invulnerable, or several enemies attack at once. Animation events can align hitboxes with a swing, but gameplay state should remain authoritative: a sprite frame change alone should not determine whether an attack can damage the player.

Debug and test the behavior

AI bugs are much easier to diagnose when the invisible decisions are drawn or displayed. Add a temporary overlay with the state, player distance, visibility, current target, path-node count, and attack cooldown. Draw the vision radius or cone, line-of-sight ray, current route, target waypoint, collision bounds, and active attack hitbox.

  • Test the player at the edge of detection range and behind a wall.
  • Test loss of sight, search completion, and return to a blocked or moved patrol point.
  • Test a missing path and an enemy that makes no progress at a corner.
  • Test attack interruption by death, stun, player movement, and invulnerability.
  • Test movement at different frame rates and after a long pause.
  • Test multiple enemies approaching the same player without all selecting an identical attack position.

Log state changes during development, but avoid logging every frame. A transition log that includes the previous and next state plus its cause is usually more useful than a stream of repeated sensor values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Scale AI updates as enemy counts grow

Rendering may run every frame, but every enemy does not need a full perception test, path search, and steering calculation on every frame. Stagger sensing and repathing across updates, reuse vectors and collections in hot loops, and share a route or flow field when many enemies pursue the same goal. Simplify distant or off-screen enemies when the game’s design permits it.

For large crowds, per-enemy A* searches can duplicate work. Shared routes, flow fields, or time-sliced searches can spread cost; gdx-ai’s pathfinding API supports interruptible searches. Keep an update budget and define what gets deferred, so a temporary burst of enemies does not force all expensive decisions into the same frame.

When to move beyond a finite-state machine

An FSM remains a good choice while each enemy has a manageable set of mutually exclusive modes. Consider a behavior tree when actions become hierarchical or reusable—for example, a selector that tries attack, then chase, then search, then patrol. Consider utility scoring when several valid actions compete and the enemy should choose based on context, such as health, distance, or incoming danger.

Neither approach is a prerequisite for a patrol guard. Start with explicit states and transitions; migrate when the FSM’s branching becomes difficult to understand or tune. Keep navigation, sensing, and attack execution separate whichever decision model you choose.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failures and fixes

  • Enemy sees through walls: range-only sensing lacks a line-of-sight test; add tile traversal or a physics raycast.
  • Enemy gets stuck at corners: direct pursuit or local steering cannot guarantee a route; use global pathfinding, detect lack of progress, and repath.
  • Enemy oscillates at a waypoint: use an arrival radius and advance the waypoint once inside it.
  • Enemy deals damage repeatedly: make the hit a one-shot event or restrict it to a bounded active window.
  • Movement changes with frame rate: multiply velocity by delta time, as in the libGDX tutorial.
  • Enemy jumps after a pause: cap the render delta for simple movement or use fixed-step simulation for physics.
  • Enemy tracks a hidden player perfectly: chase the last known position after sight is lost, then search and return.
  • Enemies overlap around the player: add separation, distinct approach points, or a limit on simultaneous attackers.
  • No route exists: handle an empty path as a normal outcome and choose a defined fallback instead of dereferencing a missing node.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.