Raycast in Unity

Hernando Nieto Jaramillo
2 min readSep 12, 2021

--

After crfeating a target reticle like this

We will want it to be able to shoot any enemy, in this case, any cube. For this, we will use a Raycast from the center of the screen.

Ray: 3D line in the 3D space used for detecting collisions, for example, for shooting bullets

Process:

  • Reference to the main camera
  • Check if lmb is pressed
  • If so, create a new Vector3 that will set the values of the camera’s center position
    The camera has a property called Viewport. The viewport represents the width and the height of the screen with values from 0 to 1, so if we want to indicate the center, the coordinates will be 0,5 and 0,5
  • Create a ray from the center of the camera
  • Create a RaycastHit hitInfo
    This variable will store the information about the object hit
  • Declare a Physics.Raycast method that will return a bool value
    If that method returns true, the code inside it will be executed, for example, the information about the gameobject hit

--

--

No responses yet