Unity 使用射線取得點擊位置資訊


建立時間: 2022年12月8日 22:37
更新時間: 2023年2月13日 09:27

說明

本篇分享關於 Unity 射線的功能,並提供用射線取得點擊位置資訊的腳本。

射線

你可以把射線想像成一隻雷射筆射出的一條線,或是蜘蛛人噴射蜘蛛絲的畫面,也許你可以使用射線來做槍枝的瞄準器,或者像我這次分享的一樣,使用射線取得點擊位置資訊。

用射線取得點擊位置資訊的腳本

3D 世界的射線

我先們看這段簡短的腳本後再來說明每段程式

Example.cs

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

public class Example : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (!Input.GetMouseButtonDown(0))
        {
            return;
        }
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100f))
        {
            // 位置資訊
            Debug.Log(hit.point);
            // 點擊物件
            Debug.Log(hit.transform.name);
        }
    }
}
  • Input.GetMouseButtonDown(0) 當使用者按下(還沒放開)滑鼠左鍵時就會返回 true。
  • Input.mousePosition 滑鼠的座標。
  • Camera.main 取得主攝影機。
  • Camera.main.ScreenPointToRay(Input.mousePosition) 返回從主攝影機穿過螢幕點的射線。
  • RaycastHit 用來記錄射線投射擊中資訊。
  • Physics.Raycast() 當射線與任何碰撞器相交時返回 true,否則返回 false。
  • Physics.Raycast(ray, out hit, 100f) out 就是將結果丟出去給一個變數接。所以這個方法就是如果 ray 與任何碰撞器相交時, hit 記錄射線投射擊中資訊,100f 代表 ray 長度。

Physics.Raycast() 返回 true 時,就可以如範例取的 hit.point 射線擊中碰撞器在世界空間中的碰撞點,關於 hit 有什麼資訊,請參考官方文件 RaycastHit 說明

對於一個初學者來說,一開始看到這段程式可能會因為看到很多陌生的類別而嚇到,但這是一個相當實用的功能,直得了解。

2D 世界的射線

Example.cs

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

public class Example : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (!Input.GetMouseButtonDown(0))
        {
            return;
        }
        Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector2.zero);

        // 判斷是否點擊到自己本身
        if (hit.collider?.gameObject == gameObject)
        {
            Debug.Log(gameObject.name);
        }
    }
}

畫出射線

射線是看不到的,如果你想看到射線,你可以使用 Debug.DrawRay() 進行偵錯

Example.cs

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

public class Example : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        Debug.DrawRay(Vector3.zero, new Vector3(2, 3, 4), Color.black);
    }
}

當你運行程式時,你會在 Scene 畫面上看到從 (0, 0, 0) 往 (2, 3, 4) 的方向射出一條黑線,Game 畫面則不會看到。

觀看次數: 1746
castrayraycastunity
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!