unity中射线检测

 射线击中物体改变物体材质

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

public class Line : MonoBehaviour
{
    Ray ray;//储存位置和方向
    public float maxDistance;
    public LayerMask layerMask;
    [SerializeField] Material material;
    private void Update()
    {
        AllRaycastCheck();
       // OneRaycastCheck();
    }
    //碰撞到第一个物体就停止检测
    public void OneRaycastCheck()
    {
        //transform.forward 跟随玩家移动改变相对位置         Vector3.forward固定世界位置

        ray=new Ray(transform.position, transform.forward);
        RaycastHit hit;
        //Physics.Raycast 只能击中一次
        //Physics.Raycast 射线  射线开始位置 方向 碰撞到的信息 最大距离 与什么图层碰撞 忽略trigger 
        if (Physics.Raycast(ray, out hit, maxDistance, layerMask, QueryTriggerInteraction.Ignore))
        {
            Debug.Log(hit.collider.gameObject.name);
            Debug.DrawLine(transform.position, hit.point, Color.red);
        }
        else
        {
            Debug.DrawLine(transform.position, transform.position+transform.forward*maxDistance, Color.green);
        }
    }
    //检测到射线上所有的物体
    public void AllRaycastCheck()
    {
        ray=new Ray(transform.position, transform.forward);
        RaycastHit[] hits;
        hits=Physics.RaycastAll(ray, maxDistance, layerMask);
        foreach(var hit in hits)
        {
            hit.collider.gameObject.GetComponent<Renderer>().material   =material;
            Debug.Log("all Ray");
        }
        Debug.DrawLine(transform.position, transform.position+transform.forward*maxDistance, Color.green);

    }

}

 物体放置鼠标点击的位置

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

public class PlaceMent : MonoBehaviour
{
    public LayerMask layerMask;
    public GameObject treeObject;
    private void FixedUpdate()
    {
      //可以用这个来改变  FindObjectOfType<PlaceMent>().treeObject;
        Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);//摄像机向屏幕鼠标位置发射一条射线
        if(Physics.Raycast(ray,out RaycastHit hitInfo,Mathf.Infinity, layerMask))//Mathf.Infinity 无限长
        {
            transform.position = hitInfo.point;
            //Quaternion.FromToRotation物体偏转角度  Vector3.up原来的角度 hitInfo.normal击中点
            transform.rotation=Quaternion.FromToRotation(Vector3.up,hitInfo.normal);
        }
        if(Input.GetMouseButtonDown(0))
        {
            Instantiate(treeObject, hitInfo.point, Quaternion.FromToRotation(Vector3.up, hitInfo.normal));
        }
    }
}

详细看

【中文专题】Raycast射线检测在3D世界中的介绍(含基本概念,武器检测,对象放置,点击角色移动等功能)-BeaverJoe-BeaverJoe-哔哩哔哩视频 (bilibili.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值