Raycasting in Unity

Download this episode

Download Video

Description

This video tutorial is a basic example on using Raycasting in Unity.

Source code here:  https://github.com/jasonrwalters/Unity_Raycast

using UnityEngine;
using System.Collections;

public class TargetDetection : MonoBehaviour
{
    private Transform tr;
    private float rotY;
    private bool targetHit;

    // Use this for initialization
    void Start()
    {
        // reference components
        tr = GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        // draws the forward facing direction
        // you do NOT need this to raycast, just for debug purposes
        DrawForward();

        // handles object rotation on the y axis
        rotY++;
        if (rotY > 360.0f) rotY = 0.0f;
        tr.eulerAngles = new Vector3(0.0f, rotY, 0.0f);

        // raycasting
        RaycastHit hit;
        Ray ray = new Ray(tr.position, tr.forward);
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.name == "Target" && !targetHit)
            {
                Debug.Log("Target was hit!");
                targetHit = true;
            }
        }
        else if (targetHit)
        {
            Debug.Log("Nothing was detected.");
            targetHit = false;
        }
    }

    void DrawForward()
    {
        Vector3 forward = tr.TransformDirection(Vector3.forward) * 2;
        Debug.DrawRay(tr.position, forward, Color.green);
    }
}

Embed

Format

Available formats for this video:

Actual format may change based on video formats available and browser capability.

    The Discussion

    Comments closed

    Comments have been closed since this content was published more than 30 days ago, but if you'd like to send us feedback you can Contact Us.