2D Direction to Target
Line up your shot. Copy the math.
How does it work? ↓How does this work?
What is a direction vector?
A direction vector (often called delta) simply answers "how far do I travel on X and Y to get to the target?". It is found by subtracting the starting point (Player) from the destination (Target). `target.x - player.x` and `target.y - player.y`.
Why normalize the vector?
If you tell a bullet to move by the direction vector directly, the bullet will instantly hit the target in one frame, because that vector spans the entire distance. A normalized vector has a length of exactly 1. By multiplying a normalized direction by a `speed` value, your object moves at a constant speed toward the target, regardless of how far away it is.
Why atan2 instead of atan?
Standard `atan(dy / dx)` doesn't know what quadrant you are in (e.g., both -Y/-X and Y/X result in positive divisions), so it only returns angles in a half-circle. `atan2(dy, dx)` takes both arguments individually, preserving their signs, allowing it to return the exact angle in a full 360-degree (2PI radians) circle. It also perfectly escapes the divide-by-zero error if `dx` is 0.
Y-Up vs Y-Down Coordinate Systems
Different engines disagree on where Y is pointing.
Y-Down: Web Canvas, Godot 2D, and Raylib treat
the top of the screen as Y=0, and Y increases as you go down. To
point 'up', dy is negative.
Y-Up: Unity and Rust/Bevy treat Y as going up like standard
math graphs.
The math is identical, but the visual
direction flips. Use the toggle above the canvas to match your
engine!