-
重载方法1:
1.需要传入Ray射线。
2.创建一个Ray射线并传参,注意射线可能与自己发生碰撞,从而Debug结果一直True,需要设置射线起点为自身之外。
-
重载方法中其他参数含义:
origin是存放起点的Vector3
maxDistance代表射线最大检测距离
out RaycastHit HitInfo是存储碰撞信息用的
layerMask是标记层级用的,射线只检测标记过的层级,Layer在这儿设置:
-
测试重载方法示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//Physics.Raycast重载1
//Ray ray = new Ray(transform.position+new Vector3 (transform.position.x,0,0), transform.forward);
//可能跟自身发生碰撞,所以要大约+一个position的x距离
//Physics.Raycast(ray);
//bool isCollider = Physics.Raycast(ray);
//Debug.Log(isCollider);
//Physics.Raycast重载2
Ray ray = new Ray(transform.position+new Vector3 (transform.position.x,0,0), transform.forward);
Physics.Raycast(ray,out RaycastHit hit);
//out RaycastHit HitInfo是存储碰撞信息用的
Debug.Log(hit.collider);
//被碰撞的信息:hit.transform。hit.collider.gameObject不能Debug,因为hit.collider可能是空指针
Debug.Log(hit.point);//碰撞到的点
//Physics.Raycast重载3
//Ray ray = new Ray(transform.position+new Vector3 (transform.position.x,0,0), transform.forward);
//bool isCollider = Physics.Raycast(ray,Mathf.Infinity,LayerMask.GetMask("Enemy1"));
//Debug.Log(isCollider);//只对Enemy1有射线检测反应
}
}