Raycasting In Unity

If you are somehow familiar with game development, you probably already know that Raycasting is used for detecting if we shoot a target by sending an invisible ray. If the ray hits on a game object of interest, we can easily gain access to the game object within script.

Here’s the link for Unity Manual for Raycast in 3D. https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

If you have been following my articles, you might remember that I have also used Raycasting in the 2.5D Platformer game, to detect if the player is grounded or not. Certainly, Raycasting can be used for many other purposes.

Back to the shooter game. Shortly, the idea is to create the ray starting from the middle of the screen, right from the center of the crosshair. Despite using the transform.position of the player might seem to work, the ray would be originated from the player’s position rather than the center of the screen. Thus, we need to make sure that the origin of the ray is the center of the camera.

I have learned that Viewport is the game view. So, I actually want to cast a ray from the center of the viewport. If you check the Unity Manual for Camera.ViewportPointToRay from here, you will observe that it is actually easy to gather the center of the camera.

Thus, the coordinate (0.5f, 0.5f) will precisely give out the center of the camera.

Shoot Script

And the result:

--

--

--

Unity Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Git — Git Flow a efficient and productive way of version control

5 Ways To Improve Your Programming Skills

Graph Search in One Line of Python Code

Build a Web Application using Django

5 ways a Christmas tree is like an old codebase

A close-up of a Christmas light on the tree branch

Reactive event processing with Reactor Core: a first look — Dominic Fox

Appium for Mobile Automation

Flutter — Notifier + Factory: A cleaner variation of setState()

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ali Emre Onur

Ali Emre Onur

Unity Developer

More from Medium

Unity Profiler- Game Dev Series 144

Setting up Git for Unity

Image Courtesy of ARreverie Technology

Light layers in Unity HDRP

Using Light Layers in Unity