Unity中使用射线查询MeshCollider背面的方法

时间:2023-03-08 20:39:17

之前遇到一个问题要从MeshCollider背面方向发出射线,直至检测到该射线与MeshCollider的相交点为止。

后来我用双面MeshCollider的方法解决了http://www.cnblogs.com/hont/p/6628841.html

但是这样又会导致许多其他问题,因为构建出来的双面MeshCollider是非临时性的。

后来我发现unity提供了一个接口Physics.queriesHitBackfaces(Unity5.5之后增加),可以解决这个问题。

测试脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class RaycastTest : MonoBehaviour
{
GameObject mCacheTipsGO; void Start()
{
mCacheTipsGO = GameObject.CreatePrimitive(PrimitiveType.Cube);
mCacheTipsGO.transform.localScale = Vector3.one * 0.3f; Destroy(mCacheTipsGO.GetComponent<Collider>());
} void Update()
{
Physics.queriesHitBackfaces = true; var raycast = default(RaycastHit);
var isHit = Physics.Raycast(new Ray(transform.position, transform.forward), out raycast, ); if (isHit)
mCacheTipsGO.transform.position = raycast.point; Physics.queriesHitBackfaces = false;
}
}

测试结果

Unity中使用射线查询MeshCollider背面的方法