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

之前遇到一个问题要从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, 20);

        if (isHit)
            mCacheTipsGO.transform.position = raycast.point;

        Physics.queriesHitBackfaces = false;
    }
}

 

 

测试结果

posted @ 2018-04-16 09:35  HONT  阅读(1504)  评论(0编辑  收藏  举报