射线碰撞单个物体:
方式1:从摄像机向世界发射一条射线,通常用于检测鼠标指针有没有选择物体
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
方式2:创建从一个点到一个方向的射线
Ray ray = new Ray(Vector3.zero,Vector3.up);
声明一个射线碰撞信息类
RaycastHit hit;
//进行碰撞检测并返回结果,检测信息会写入碰撞信息类
bool res = Physics.Raycast(ray,out hit);
射线碰撞多个物体:
//从摄像机向游戏世界发射一条射线,常用于检测鼠标是否选中物体
Ray ray = Camera.main.ScreenPositionToRay(Input.mousePosition);
//声明一个碰撞信息数组
Raycast[] hits;
//射线检测,并返回所有碰撞信息
hits = Phsics.RaycastAll(ray);
hits = Phsics.RaycastAll(Vector3.zero,Vector3.up);
//添加射线检测的距离设置
hits = Phsics.RaycastAll(ray,100);
hits = Phsics.RaycastAll(Vector3.zero,Vector3.up,100);
//只与第10(某)个图层上的物体相撞
hits = Physics.RaycastAll(ray,1000,1<<10);
hits = Physics.RaycastAll(Vector3.zero,Vector3.up,1000,1<<10);
例:可以用射线检测人物与地面的距离
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Raycasting : MonoBehaviour
{
public float height;
RaycastHit hit;
void Update()
{
Ray ray = new Ray(transform.position, -Vector3.up);
Debug.DrawRay(transform.position,Vector3.down * height,Color.red);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.CompareTag("Ground"))
{
// Debug.Log(hit.distance);
Debug.Log(hit.distance - 0.5f);
}
}
}
}