Unity3D:检测网格与其他游戏对象相交的三角形

问题描述 投票:0回答:1

我有一个平面,包含多个网格(像往常一样)。现在,我向场景中添加了新的游戏对象 - 圆柱体。当圆柱体与平面碰撞时,我需要检测平面的所有三角形,出现在圆柱体内部。可以使用Unity3D API吗?
我看到了教程“碰撞体作为触发器”,但我有一个问题 - 我可以在碰撞对象中没有 Rigidbody 组件的情况下处理触发事件吗?由于某些原因,我无法在平面和圆柱体中使用刚体。

3d unity-game-engine collision-detection intersection
1个回答
2
投票

这可以通过向圆柱体添加球体投射来实现,并且当任何对象进入其中时(盒子碰撞器、光线投射等)都会发生一些事件。为了检测平面的三角形(假设您有某种网格碰撞器),您可以获得圆柱体球体投射内所有击中对象的列表,并循环遍历组成完整网格三角形的每个对象。这是一些显示该过程的代码:

void GetMeshTriangle(RaycastHit meshHitPoint, MeshCollider meshObject)
{
    Mesh mesh = meshObject.sharedMesh;
    Vector3[] vertices = mesh.vertices;
    int[] triangles = mesh.triangles;
    int counter = 0;
    for(int n = 0; n <= worldObjectsHit.Length * 3; n++)
    {
        if (counter == 2 )
        {
            Transform hitTransform = meshHitPoint.collider.transform;
            try
            {
                Vector3 pointOne = vertices[triangles[meshHitPoint.triangleIndex * 3 + n]];
                Vector3 pointTwo = vertices[triangles[meshHitPoint.triangleIndex * 3 + ( n-1 )]];
                Vector3 pointThree = vertices[triangles[meshHitPoint.triangleIndex * 3 + ( n-2 )]];
                pointOne = hitTransform.TransformPoint( pointOne );
                pointTwo = hitTransform.TransformPoint( pointTwo );
                pointThree = hitTransform.TransformPoint( pointThree );
                Vector3 meshObjectCenter = new Vector3( ( ( pointOne.x + pointTwo.x + pointThree.x ) / 3 ), 
                                               ( ( pointOne.y + pointTwo.y + pointThree.y ) / 3 ) , 
                                               ( ( pointOne.z + pointTwo.z + pointThree.z ) / 3 ) );
                Debug.DrawLine( p0, p1 );
                Debug.DrawLine( p1, p2 );
                Debug.DrawLine( p2, p0 );
                IsMeshColliding( meshHitPoint, meshObjectCenter );
                } 
                catch ( System.IndexOutOfRangeException ex )
                {
                    break;
                }
                counter = 0;
            } 
            else 
            {
                counter++;
            }
        }
    }
}

在“IsMeshColliding( )”行,您可以添加自己的逻辑以使某种事件发生。

© www.soinside.com 2019 - 2024. All rights reserved.