Angles and Rotation in Games
How do enemies know where to aim?
How do enemies know where to aim?
In games, we often need objects to face toward a target. A turret needs to aim at the player. An enemy needs to look where it's going. Move your mouse to see the problem!
Move your mouse - the turret needs to aim at you!
We know the turret position (250, 200) and the target position. How do we calculate the angle to rotate?
We need a function that converts X,Y coordinates into an angle. That function is called atan2!
Before we calculate angles, we need to understand two ways to measure them. Humans like degrees (0° to 360°), but computers prefer radians. Drag the slider to see how they relate!
Full circle = 360°
Familiar to humans
Full circle = 2π ≈ 6.28
Used by computers
One radian is the angle where the arc length equals the radius. This makes math with circles much simpler! All trig functions in programming (sin, cos, atan2) use radians.
atan2(y, x) is every game developer's best friend. Give it the difference in Y and X coordinates,
and it returns the angle! Click anywhere to see it in action.
Click anywhere to set a target point
In screen coordinates, Y increases downward. So "up" is negative Y. atan2 handles this correctly!
Unlike regular atan(), atan2() works in all four quadrants and never divides by zero.
Now let's put it together! Watch how a turret uses atan2 to track your mouse. You can toggle smooth rotation to see the difference between instant aiming and realistic rotation.
Real games use smooth rotation with a maximum turn speed. This makes turrets feel realistic and gives players a chance to dodge! Some games also add prediction to aim where the player WILL be.
The flip side of finding angles is using angles to find positions. cos(angle) gives you the X component,
and sin(angle) gives you the Y component. This creates circular motion!
Orbiting enemies, rotating platforms, bullet patterns, radar sweeps, and oscillating objects!
cos(angle) returns -1 to 1 for X, sin(angle) returns -1 to 1 for Y. Multiply by radius to scale!
Put your knowledge to the test! Control a turret and shoot down enemies before they reach the center. Click to shoot in the direction you're aiming.
You've learned the secrets of angles and rotation! From turrets to orbits, you now understand how games make things point, spin, and move in circles.
Computers use radians (2π = full circle)
The magic function that finds angles from coordinates
Limiting turn speed for realistic movement
Convert angles back to X,Y positions for circular motion
Put your new knowledge into practice!