[Unity] Physics: I tried “Physics. Spherecast”.

Before, I tried “Physics.Raycast”, then I wrote the results in this blog.

[Link: Physics: I tried “Physics.Raycast” from Game Object.]
[Link: Physics: I tried “Physics.Raycast” from Camera.]

This time, I’ll introduce other Casting methods under Physics class. (However, I think that “Raycast” is the most popular and used high frequently.)

[Ref: https://docs.unity3d.com/ScriptReference/Physics.html]

 

[Some Cast methods under Physics class]

BoxCast Casting Box shaped Ray, check whether hit the ray to any objects which have object collider. If hit to something, return the detail information about the hit.
CapsuleCast Casting Capsule shaped Ray, check whether hit the ray to any objects which have object collider. If hit to something, return the detail information about the hit.
Linecast Put a line from the starting point to the ending point you defined, and check whether something hit to the line. If hit something which has object collider to the line, return ‘true’.
Raycast Casting laser beam from ‘Origin’ to ‘direction’ until ‘maxDistance’ you set, check whether hit the ray to any objects which have object collider. If hit to something, return the detail information about the hit.
SphereCast Casting Sphere shaped Ray, check whether hit the ray to any objects which have object collider. If hit to something, return the detail information about the hit.

 

[Example to use “Spherecast”]

This time, I tried “Spherecast”.

Firstly, please see the movie which is used ‘Spherecast” function. The semi-transparent yellow object indicates rough area of Sphere shape Ray casted. The red line is drawn to an object hit by the Ray in the area.

As you can see, when Unity-chan (free character of Unity Japan) enter into the area, Ray is hit to her, and red line is drawn to her.

 

[One important point for “Spherecaset”]

There is one important point for this Spherecast, it’s the shape of the area to be casted the Ray.
I created a 3D model of the shape of the area by Blender to be understand easily.

Can you notice? There is a sphere area around casting point.
Therefore, in above example movie, when Unity-chan enter into the sphere area, Ray cannot be hit to her, then the red line move to another object.

 

[Source code for this test]

(It’s very simple this time.)

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

public class Spherecast_Test : MonoBehaviour {

   void Update () {
		
      RaycastHit hit;

      // If Ray hit something
      if (Physics.SphereCast (transform.position, 3, 
                transform.forward, out hit, 10)) {

         // Draw Red Line
         Debug.DrawLine(transform.position, hit.point, Color.red);
      }
   }
}

 

[Original Japanese Site: http://blog.lab7.biz/archives/4062155.html]

 

Leave a Reply

Your email address will not be published. Required fields are marked *