pageTitleCS

rayTitleRaycasting is basically what it says on the tin. It is casting or drawing a ray or line from one point to another in order to detect what it hits. This is very useful and an essentail element to scripting games in Unity. Here we will look at how to implement this system and debug it. 

Step 1:
To start with we will create a new script called castScript and attach it to an object in the game scene. We then need to set up some variables to hold information such as the ray origin and range of the ray. origin is where you want the ray to be cast from, in our example it is the FPS camera and range is the distance you want the check for collision. We then use a Debug.DrawRay to show in the scene view what is happening with the ray.
ray001

JS

#pragma strict

var origin : Transform;
var range : float;
private var ray = new Ray(origin.position, origin.forward);
private var hit : RaycastHit;

function Update () {

 Debug.DrawRay (origin.position, origin.forward * range, Color.yellow);
    
}

C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class castScript : MonoBehaviour {

public Transform origin;
public float range;
Ray ray = new Ray(origin.position, origin.forward);
RaycastHit hit;

void Update () {

 Debug.DrawRay (origin.position, origin.forward * range, Color.yellow);

    
}

}

Step 2:
Now we need to actually check for collisions along the ray. this is done by using Physics Raycast. the red example prints the name of the object hit by the ray. The green example checks to see if the object hit has a tag called enemy and if it does destroys it.

JS

#pragma strict

var origin : Transform;
var range : float;
private var ray = new Ray(origin.position, origin.forward);
private var hit : RaycastHit;

function Update () {

 Debug.DrawRay (origin.position, origin.forward * range, Color.yellow);
 if(Physics.Raycast (ray, hit, range))
         {
               Debug.Log(hit.collider.name);

              if(hit.collider.tag == "enemy")
               {
                    Destroy(hit.collider.gameObject);
              }
          }
    
}

C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class castScript : MonoBehaviour {

public Transform origin;
public float range;
Ray ray = new Ray(origin.position, origin.forward);
RaycastHit hit;

void Update () {

 Debug.DrawRay (origin.position, origin.forward * range, Color.yellow);
     if(Physics.Raycast (ray, hit, range))
         {
               Debug.Log(hit.collider.name);
                if(hit.collider.tag == "enemy")
               {
                    Destroy(hit.collider.gameObject);
              }

          }

}

}

Casino Bet 365 is best casino in the world.

What's Next

Next up for Unity Snippets is a look at game development articles from across the web...

Free Templates - bigtheme.net
Popular Art Betting make bookies articles.