You know, we normally use “Raycast” to identify Game Objects existed in certain direction from one location.
The image is like that you emit virtual laser beam from a certain position, then if the beam hit somethings, you’ll get the information of the objects.
2 ways for Raycast
The method of this, there are 2 ways like following
- Cast a Ray from a Game Object
To identify the objects which exist in certain direction from a Game Object on a Scene. - Cast a Ray from a Camera
To identify the objects which exist beyond the certain point on the camera screen.
For example, if there are no objects between NPC and Player, NPC try to shoot to the Player, or User select some Game Objects in 3D space by clicking those on a screen…
Depending on your creative ideas, you can create many kinds of games by these ways to identify game objects in a scene.
Ok, let’s try.
(Ref: https://docs.unity3d.com/ScriptReference/Physics.Raycast.html )
Cast a Ray from a Game Object
“Third Person Controller” which is Unity standard 3D model is automatically directing to “Unity-chan” which is free character of Unity Japan player is controlling.
If there are not any obstacles between the 2 characters, then “Third Person Controller” can see “Unity-chan” directly, a red laser beam will be appeared.
This is the demo, the left window is Game view, and the right window is Scene view.
The C# source code for Raycast applied to “Third Person Controller”.
public class Raycast_Test : MonoBehaviour { public Transform target; RaycastHit hit; void FixedUpdate() { // Face to target direction transform.rotation = Quaternion.LookRotation (target.position - transform.position); // Create 'Ray' to forward direction Ray ray = new Ray(transform.position, transform.forward); // If Ray hit someting if (Physics.Raycast (ray, out hit, 15)) { // If the object is "Player" if (hit.collider.tag == "Player") { // Draw Red Line Debug.DrawLine(ray.origin, hit.point, Color.red); } } } }
Regarding “Cast a Ray from a Camera”, I’ll explain it next time.
[Original Japanese Site: http://blog.lab7.biz/archives/2256403.html]