FPS射线检测

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/PR_sc/article/details/85469138
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);//销毁球体
    }
}

猜你喜欢

转载自blog.csdn.net/PR_sc/article/details/85469138