Unity 四、常用脚本(十五)Ray射线

 照相机射线

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

public class TestRay : MonoBehaviour
{
    void Update()
    {
        MyTestRay();
    }
    void MyTestRay()
    {
        #region 照相机射线
        if (Input.GetMouseButtonDown(0))//鼠标左击
        {
            //从照相机发射一条射线到场景中屏幕点击的位置
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //射线碰撞数据对象
            RaycastHit hit;
            //碰撞到物体
            if (Physics.Raycast(ray, out hit))
            {
                //在场景窗口画一条线
                Debug.DrawLine(Camera.main.transform.position, hit.point, Color.red);
            }
        }
        #endregion
    }

}

射线连接两点

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

public class TestRay : MonoBehaviour
{
    public Transform mLight;//灯光Transform
    public Transform mCube;//Cube1Transform
    void Update()
    {
        MyTestRay();
    }
    void MyTestRay()
    {
        #region 射线连接两点
        if (Physics.Raycast(mLight.position, mCube.position - mLight.position))
        {
            //在场景窗口画一条线
            Debug.DrawLine(mLight.transform.position, mCube.position, Color.red);
        }
        #endregion
    }

}

    

物体移动到鼠标单击位置

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

public class TestRay: MonoBehaviour
{
    //要移动的物体
    public Transform cube;
    void Update()
    {
        PointMove();
    }
    void PointMove()
    {
        if (Input.GetMouseButtonDown(0))//鼠标左击
        {
            //从照相机发射一条射线到屏幕点击的位置
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //碰撞数据类
            RaycastHit hit;
            //计算射线是否碰撞物体
            if (Physics.Raycast(ray, out hit))
            {
                //控制台输出日志
                Debug.Log("移动到" + hit.point);
                //实现移动
                cube.transform.position = hit.point;
            }
        }
    }
}

射击销毁物体

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

public class TestRay: MonoBehaviour
{
    void Update()
    {
        Shoot();
    }
    void Shoot()
    {
        if (Input.GetMouseButtonDown(0))//鼠标左击
        {
            //从照相机发射一条射线到屏幕点击的位置
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //碰撞数据类
            RaycastHit hit;
            //计算射线是否碰撞物体
            if (Physics.Raycast(ray, out hit))
            {
                //控制台输出日志
                Debug.Log("获取到" + hit.point);
                //实现销毁
                DestroyObject(hit.transform.gameObject);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/NCZ9_/article/details/88665342