【问题标题】:Unity3D: detect triangles of mesh intersects with other gameObjectUnity3D:检测网格的三角形与其他游戏对象相交
【发布时间】:2014-02-22 13:15:55
【问题描述】:

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

【问题讨论】:

    标签: 3d unity3d collision-detection intersection


    【解决方案1】:

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

    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( )”行,您可以添加自己的逻辑以使某种事件发生。

    【讨论】:

    • thnx for SphereCast 提示。我将检查网格的每个三角形是否与 Cylinder 重叠(使用 SphereCastOverlapSphere 方法)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多