unity3d Raycast Physics Raycast


Example

This function casts a ray from point origin in direction direction of length maxDistance against all colliders in the scene.

The function takes in the origin direction maxDistance and calculate if there is a collider in front of the GameObject.

Physics.Raycast(origin, direction, maxDistance);

For example, this function will print Hello World to the console if there is something within 10 units of the GameObject attached to it:

using UnityEngine;

public class TestPhysicsRaycast: MonoBehaviour 
{
    void FixedUpdate() 
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        
        if (Physics.Raycast(transform.position, fwd, 10)) 
            print("Hello World");
    }
}