Raycasting
An invisible line that tells you what it hits first.
A ray is a question: "if I draw a line from here in this direction, what do I hit first, and where?" Games ask it constantly: is the floor under me, can the enemy see the player, what is the mouse pointing at, did the bullet hit. It is cheap, precise and works the same in 2D and 3D.
Try this: Aim past a crate at the coin behind it, then shorten the ray with ↓ until it stops short.
rayhit pointsurface normal
Aim with the arrows or the pointer.
Prompt bit
Works for 2D or 3D in any engine (Unity, Unreal, Godot, web). Paste the short one for a quick fix, or the detailed one when you want it done properly.
Use raycasts for line-of-sight and hit checks: cast from the origin along a normalized direction with a max distance and a layer mask that excludes the caster, take only the closest hit, and cache results for 0.1 s when many enemies check every frame.
Add a small raycast helper and use it for ground checks, line of sight, mouse picking and hitscan (2D or 3D, any engine). Always pass an origin, a normalized direction, a max distance and a layer mask; exclude the caster's own colliders (start slightly outside them or use the mask). Use the closest hit (hit point, normal, distance, collider) unless you explicitly want all hits, which most engines return unsorted, so sort by distance. Mouse picking: build the ray from the camera through the cursor (ScreenPointToRay or equivalent), not from the player. Line of sight: cast from the enemy eyes to the player chest and treat any hit that is not the player as blocked. For wide things (characters, thick bullets) use a sphere or box cast instead of a ray so they cannot slip through gaps. Use the hit normal to place decals and bounce projectiles. Limit expensive checks: AI sight 5 to 10 times a second (cache for 0.1 to 0.2 s) rather than every frame. Draw debug lines for every cast in development builds.
Where it's used
- Shooters: hitscan weapons, headshots, laser sights
- 3D games: mouse picking, click-to-move and object selection
- AI: enemy line of sight and cover checks
- Character controllers: ground checks, ledge and wall detection
- Cameras and placement: stop the camera clipping walls; place buildings on terrain
Common mistakes
Starting the ray inside the caster so it always hits itself, passing an unnormalized direction or infinite distance, assuming "hit all" results are sorted, and using a thin ray where a sphere cast is needed so characters squeeze through gaps.
Writing this with an AI assistant? See our best AI coding assistants for game developers.
Missing a concept? Request one.



