Tuesday, 24 November 2015

Ray Tracing

Ray Tracing is a type of collision detection used in Unity, that is commonly used in various entities like AI enemies. Basically when something is raytracing it's separate from the collision box around it, but instead of having a box around it the object is casting an invisible line forward in any direction, that activates when something hits it. This can range from an enemy walking around, casting a ray on the floor so that it doesn't fall off a ledge, to using a raycast to look around the world to try and spot the player, and when the player comes into contact with the beam the enemy gives chase.

As helped by (RayCast, 2015), from the official Unity website. Here is some code that can be used for Raytracing and I'll explain how it works: "using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, fwd, 10)) {
            print("There is something in front of the object!");
        }
    } 
}"

This is a simple C# script that will cast a ray, and it'll be able to detect all of the other colliders in your Unity game scene. So when two colliders hit each other they will both trigger a reaction depending on what you want your program to happen. Also as a side note, if the object emitting the raycast already has a collider attached to it, the ray will not interact with it when it is spawned.

Here's a basic diagram showing how raytracing works, made by me:

No comments:

Post a Comment