Click.
Bam!
BOOM💥
START
Drag squares to interact

Code Snippet

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!

Answers to Common Developer Questions

How do you find the direction vector between two points?
Subtract the target's position from the origin's position: Target(x,y) - Origin(x,y). This results in a vector pointing exactly from the origin to the target.
Why do we Normalize direction vectors?
Normalization mathematically forces a vector's length (magnitude) to exactly 1.0 without changing its direction. This is critical for movement calculations so an entity moves at a constant logical speed rather than accelerating based on distance.
How do you calculate the exact angle to a target in 2D?
Find the direction vector, then use the Math.atan2(dir.y, dir.x) function. This returns the mathematically correct angle in radians, which you can use to rotate your game object to face the target.