[Unity] Physics: I tried “Physics.Raycast” from Camera.

Last time, I tried Raycast by casting Ray from a game object.

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

This time, I tried another way of Raycast. That is casting Ray from Camera.

[Ref: https://docs.unity3d.com/Manual/CameraRays.html]

 

[Test image to cast Ray from Camera]

When clicking a game object which are scattered in 3D space by mouse, the shape and color (object name and tag) are shown.

 

[Source code for this test]

The C# source code which is attached to Camera object is following.

public class Raycast_Test_2 : MonoBehaviour {

    public Text textObjectName;
    public Text textObjectTag;

    void Update () {

        // If mouse button is clicked
        if (Input.GetMouseButtonDown(0)) {

            // Create Ray
            Ray ray = 
              Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit = new RaycastHit();

            // If Ray hit something
            if (Physics.Raycast(ray, out hit, 10)) {

                // Show Name and Tag of the object
                string objectName = hit.collider.gameObject.name;
                textObjectName.text = objectName;
                string objectTag = hit.collider.gameObject.tag;
                textObjectTag.text = objectTag;
            }
        }
    }
}

 

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

 

Leave a Reply

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