【Unity3d】Ray射線初探-射線的原理及用法


http://www.xiaobao1993.com/231.html

 

射線是一個無窮的線,開始於origin並沿着direction方向。
當射線碰到物體后。它就會停止發射。

 

在屏幕中拉一個CUBE,並用鼠標點擊它

 

using UnityEngine;
using System.Collections;

public class TestRay : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Debug.Log("xxxxxxxxxxxxxxxxxxxxxx");

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//從攝像機發出到點擊坐標的射線
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                Debug.DrawLine(ray.origin, hitInfo.point);//划出射線,在scene視圖中能看到由攝像機發射出的射線
                GameObject gameObj = hitInfo.collider.gameObject;
                if (gameObj.name.StartsWith("Cube") == true)//當射線碰撞目標的name包含Cube,執行拾取操作
                {
                    Debug.Log(gameObj.name);
                }
            }
        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM