Lesson 30 +10 XP

Physics Materials & Raycasting

Physics Materials & Raycasting

Physic Materials

A Physic Material defines the friction and bounciness of colliding surfaces.

  • Friction: Resistance to sliding (0 means slides like ice, higher values slide less).
  • Bounciness: How much velocity is retained upon impact (0 means no bounce, 1 means a perfect bounce).

You create a Physic Material in your Assets folder and assign it to the "Material" field on a Collider component.

Raycasting

Raycasting is the process of shooting an imaginary ray (a line) from a point in a direction to see if it hits any colliders. It is used for shooting weapons, checking if a character is grounded, or finding objects under the mouse cursor.

Physics.Raycast syntax

To cast a ray in C#:

void Update()
{
    Vector3 origin = transform.position;
    Vector3 direction = transform.forward;
    RaycastHit hit;
    float maxDistance = 10f;

    if (Physics.Raycast(origin, direction, out hit, maxDistance))
    {
        Debug.Log("Hit object: " + hit.collider.name);
        Debug.DrawLine(origin, hit.point, Color.red);
    }
}

Key variables:

  • RaycastHit hit: A structure that gets filled with details about what was hit (hit point, distance, collider).
  • out hit: The out keyword tells C# that the method will write results into this variable.
  • Physics.Raycast: Returns true if a collider was hit, and false if the ray hit nothing.

TL;DR

  • Physic Materials define friction and bounciness on Colliders.
  • Raycasting casts an imaginary ray from an origin in a direction.
  • Physics.Raycast returns true on hitting a collider.
  • Use out RaycastHit to get hit coordinates, distance, and collider references.