FPS射線檢測

using UnityEngine;
using System.Collections;

public class RayShooter : MonoBehaviour
{
    [SerializeField] private AudioSource soundSource;//[SerializeField] private 強制unity去序列化一個私有域
    [SerializeField] private AudioClip hitWall;//序列化的意思是說再次讀取Unity時序列化的變量是
    [SerializeField] private AudioClip hitEnemy;// 有值的,不需要你再次去賦值,因爲它已經被保存下來

    private Camera _camera;

    void Start()
    {
        _camera = GetComponent<Camera>();//獲取相機上的Camera組件

        Cursor.lockState = CursorLockMode.Locked;//鎖定時,光標將自動居視圖中間,並使其從不離開視圖
        Cursor.visible = false;//隱藏光標
    }

    void OnGUI()// 創建子彈準星
    {
        int size = 12;
        float posX = _camera.pixelWidth / 2 - size / 4;//camera.pixelWidth: 相機的像素寬度(不考慮動態分辨率縮放)(只讀)。
        float posY = _camera.pixelHeight / 2 - size / 2;// 使用此選項可返回“攝影機”視口的寬度(以像素爲單位)。這是隻讀的
        GUI.Label(new Rect(posX, posY, size, size), "*");// 在屏幕中顯示子彈準星
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))//當點擊左建執行發射射線
        {
            Vector3 point = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight / 2, 0);//發射位置
            Ray ray = _camera.ScreenPointToRay(point);//創建射線
            RaycastHit hit;//數據結構變量
            if (Physics.Raycast(ray, out hit))//在此方法中尋找射線信息,並且賦值給hit變量
            {
                GameObject hitObject = hit.transform.gameObject;//獲取射線交叉的對象
                //獲取射線與射擊到物體的交叉位置,並且進行一些操作
                ReactiveTarget target = hitObject.GetComponent<ReactiveTarget>();//試着獲取此對象ReactiveTarget腳本組件
                if (target != null)//如果有此組件的,說明是敵人。
                {
                    target.ReactToHit();
                    soundSource.PlayOneShot(hitEnemy);
                }
                else
                {
                    StartCoroutine(SphereIndicator(hit.point));//運行此協程
                    soundSource.PlayOneShot(hitWall);
                }
            }
        }
    }

    private IEnumerator SphereIndicator(Vector3 pos)
    {                              //射線檢測
        GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);//創建一個帶有基本網格渲染器和相應碰撞器的遊戲球體。
        sphere.transform.position = pos;

        yield return new WaitForSeconds(1);//Yield Return關鍵字的作用就是退出當前函數,並且會保存當前函數執行到什麼地方,也就上下文
        // WaitForSeconds(1):等待一秒執行語句
        Destroy(sphere);//銷燬球體
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章