Understanding Raycasting in Games
What a raycast is and how games use it for line of sight, shooting, ground checks and interaction — explained from the ground up.
A raycast is one of the most useful tools in game development: you fire an invisible ray from a point in a direction and ask "what's the first thing it hits, and where?" That simple question powers a surprising amount of gameplay.
The core idea
A ray has an origin (a point) and a direction (which way it points). The engine marches that ray forward until it intersects something — a wall, an enemy, the ground — and returns a hit: what was struck, the exact point, the distance, and often the surface normal (which way the surface faces). If it hits nothing, you get no hit.
What raycasts are used for
- Shooting (hitscan): instant-hit weapons cast a ray from the gun; the first thing hit takes damage. No bullet to simulate.
- Line of sight: cast from an enemy to the player — if the ray hits a wall first, the enemy can't see you. This is the backbone of stealth and AI awareness.
- Ground checks: cast a short ray downward from a character to know if they're standing on something (for jumping/falling logic).
- Interaction: cast from the camera or cursor to find what the player is pointing at ("press E to open").
- Sensors: cast ahead of an AI to detect walls or ledges so it turns instead of walking off.
Length and layers matter
Two things keep raycasts efficient and correct:
- Max distance: don't cast infinitely — a ground check only needs a few pixels/units. Shorter rays are cheaper and avoid false hits.
- Layers/masks: tell the ray what to consider. A line-of-sight check should hit walls but ignore pickups; a ground check should hit terrain but ignore the character itself.
Rays vs. shapecasts
A pure ray is infinitely thin, so it can slip between objects or through corners. When you need thickness — a wide laser, a fat bullet, a character's body — engines offer a shapecast (cast a circle/box along the direction) that behaves like a thick ray.
Mental model
Think of a raycast as a question, not a thing you draw: "starting here, going this way, what do I hit first?" Once you see gameplay problems as ray questions — can it see me? am I grounded? what did I click? — you'll reach for raycasting constantly.