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);
            }
        }
    }
}

 

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值