Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Unity Raycast and highlighting mesh triangle of intersection

Discussion in 'Editor & General Support' started by TheSituation, Jun 21, 2020.

  1. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
    I would like to fire a ray, and highlight the triangle of the point on a mesh where the collision occurs.

    I have the following code, which runs when I left mouse click, myEyes is my FPS camera.:

    Code (CSharp):
    1. void Dig()
    2. {
    3.     Ray ray = new Ray(myEyes.transform.position, myEyes.transform.forward);
    4.     Debug.DrawRay(ray.origin, ray.direction * 50f, Color.cyan, 2000f) ;
    5.     RaycastHit hit;
    6.  
    7.  
    8.     // if(Physics.Raycast(ray, out hit,1000f, LayerMask.NameToLayer("Ground"))) -- this dos not work - debug line shows ray is hitting layer 8 == ground but with the mask, nothing is hit?
    9.     if (Physics.Raycast(ray,out hit, 50f))
    10.     {
    11.  
    12.         //remove a 'spades' worth of voxels, if pointing at the terrain, and shove them somewhere random nearby.
    13.         Debug.Log("Tag is:" + hit.collider.gameObject.tag + " and object name is:" + hit.collider.gameObject.name + "And layer is:" + hit.collider.gameObject.layer);
    14.  
    15.  
    16.         MeshCollider meshCollider = hit.collider as MeshCollider;
    17.         if (meshCollider == null || meshCollider.sharedMesh == null)
    18.             return;
    19.  
    20.        
    21.         Mesh mesh = meshCollider.sharedMesh;
    22.         Vector3[] vertices = mesh.vertices;
    23.         int[] triangles = mesh.triangles;
    24.         Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
    25.         Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
    26.         Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
    27.         Transform hitTransform = hit.collider.transform;
    28.         p0 = hitTransform.TransformPoint(p0);
    29.         p1 = hitTransform.TransformPoint(p1);
    30.         p2 = hitTransform.TransformPoint(p2);
    31.         Debug.DrawLine(p0, p1,Color.red,1000f);
    32.         Debug.DrawLine(p1, p2, Color.red, 1000f);
    33.         Debug.DrawLine(p2, p0, Color.red, 1000f);
    34.  
    35.  
    36.     }
    37.     else{
    38.         Debug.Log("Hit nothing");
    39.     }
    40. }
    The outcome of this is the following: huh3.png

    Note that triangles are indeed highlighted - but they are nowhere near the collision point? Can somebody highlight why.

    Also, the Debug output from this example is :

    Code (CSharp):
    1. Tag is:Terrain and object name is:Chunk (0, 0, 0)And layer is:8
    2. UnityEngine.Debug:Log(Object)
    3. Tag is:Terrain and object name is:Chunk (0, 0, 0)And layer is:8
    4. UnityEngine.Debug:Log(Object)
    5. Tag is:Terrain and object name is:Chunk (0, 0, 0)And layer is:8
    6. UnityEngine.Debug:Log(Object)
    7. Tag is:Terrain and object name is:Chunk (0, 0, 0)And layer is:8
    8. UnityEngine.Debug:Log(Object)
    9. Tag is:Terrain and object name is:Chunk (0, 0, 0)And layer is:8
    10. UnityEngine.Debug:Log(Object)
    11. Tag is:Terrain and object name is:Chunk (0, 0, 0)And layer is:8
    12. UnityEngine.Debug:Log(Object)
    My "Ground" layer is layer 8 - and when I try a Raycast with a layerMask - it fails to hit anything at all, I have no idea why. This line casts the ray with such a mask, and causes the if condition to fail, resulting in it dropping into the "Hit Nothing" debug output line.

    Any help would be very much appreciated.
     
  2. fffMalzbier

    fffMalzbier

    Joined:
    Jun 14, 2011
    Posts:
    3,276
    The script in general seems to be working.
    Tested it with a default plane and the myEyes set to the main camera.
     
  3. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
    Is it therefore something to do with my mesh?!
     
  4. fffMalzbier

    fffMalzbier

    Joined:
    Jun 14, 2011
    Posts:
    3,276
    You could try it with a Default plane and if that is working fine in your project its probably the mesh.
    is that terrain object scaled?
     
    Last edited: Jun 23, 2020
  5. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,346
    This is wrong:

    Code (csharp):
    1. if(Physics.Raycast(ray, out hit,1000f, LayerMask.NameToLayer("Ground")))
    You need a layermask that targets the ground layer, while NameToLayer gives you that layer's index, which is not the same thing.

    So if ground is layer 8, LayerMask.NameToLayer gives 8, while the mask you want is 1 << 8, which is 0b100000000 or 256.

    You should read up on bitmasks if that's confusing! Or check the layermask docs. For a simpler solution, simply use a public LayerMask field, and use that as your layermask.
     
    TheSituation and fffMalzbier like this.
  6. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
    Great - got it thanks @Baste i'll read up on this. - I changed it to int layerMaskGround = 1 << LayerMask.NameToLayer("Ground") and it works now, despite me not fully understanding it - will read the docs as you suggest.

    This is my MeshGenerator class - can you take a look and maybe help see why this strange behaviour occurs when selecting the triangle where the collision occurs?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [ExecuteInEditMode]
    6. public class MeshGenerator : MonoBehaviour
    7. {
    8.  
    9.     const int threadGroupSize = 8;
    10.  
    11.     [Header("General Settings")]
    12.     public DensityGenerator densityGenerator;
    13.  
    14.     public bool fixedMapSize;
    15.     [ConditionalHide(nameof(fixedMapSize), true)]
    16.     public Vector3Int numChunks = Vector3Int.one;
    17.     [ConditionalHide(nameof(fixedMapSize), false)]
    18.     public Transform viewer;
    19.     [ConditionalHide(nameof(fixedMapSize), false)]
    20.     public float viewDistance = 30;
    21.  
    22.     [Space()]
    23.     public bool autoUpdateInEditor = true;
    24.     public bool autoUpdateInGame = true;
    25.     public ComputeShader shader;
    26.     public Material mat;
    27.     public bool generateColliders;
    28.  
    29.     [Header("Voxel Settings")]
    30.     public float isoLevel;
    31.     public float boundsSize = 1;
    32.     public Vector3 offset = Vector3.zero;
    33.  
    34.     [Range(2, 100)]
    35.     public int numPointsPerAxis = 30;
    36.  
    37.     [Header("Gizmos")]
    38.     public bool showBoundsGizmo = true;
    39.     public Color boundsGizmoCol = Color.white;
    40.  
    41.     GameObject chunkHolder;
    42.     const string chunkHolderName = "Chunks Holder";
    43.     List<Chunk> chunks;
    44.     Dictionary<Vector3Int, Chunk> existingChunks;
    45.     Queue<Chunk> recycleableChunks;
    46.  
    47.     // Buffers
    48.     ComputeBuffer triangleBuffer;
    49.     ComputeBuffer pointsBuffer;
    50.     ComputeBuffer triCountBuffer;
    51.  
    52.     bool settingsUpdated;
    53.  
    54.     void Awake()
    55.     {
    56.         if (Application.isPlaying && !fixedMapSize)
    57.         {
    58.             InitVariableChunkStructures();
    59.  
    60.             // var oldChunks = FindObjectsOfType<Chunk> ();
    61.             // for (int i = oldChunks.Length - 1; i >= 0; i--) {
    62.             //     Destroy (oldChunks[i].gameObject);
    63.             //  }
    64.         }
    65.     }
    66.  
    67.     void Update()
    68.     {
    69.         // Update endless terrain
    70.         if ((Application.isPlaying && !fixedMapSize))
    71.         {
    72.             Debug.Log("In normal application update path");
    73.             Run();
    74.         }
    75.  
    76.         if (settingsUpdated)
    77.         {
    78.             Debug.Log("In settings updated");
    79.             RequestMeshUpdate();
    80.             settingsUpdated = false;
    81.         }
    82.     }
    83.  
    84.     public void Run()
    85.     {
    86.         CreateBuffers();
    87.  
    88.         if (fixedMapSize)
    89.         {
    90.             InitChunks();
    91.             UpdateAllChunks();
    92.  
    93.         }
    94.         else
    95.         {
    96.             if (Application.isPlaying)
    97.             {
    98.                 InitVisibleChunks();
    99.             }
    100.         }
    101.  
    102.         // Release buffers immediately in editor
    103.         if (!Application.isPlaying)
    104.         {
    105.             ReleaseBuffers();
    106.         }
    107.  
    108.     }
    109.  
    110.     public void RequestMeshUpdate()
    111.     {
    112.         if ((Application.isPlaying && autoUpdateInGame) || (!Application.isPlaying && autoUpdateInEditor))
    113.         {
    114.             Run();
    115.         }
    116.     }
    117.  
    118.     void InitVariableChunkStructures()
    119.     {
    120.         recycleableChunks = new Queue<Chunk>();
    121.         chunks = new List<Chunk>();
    122.         existingChunks = new Dictionary<Vector3Int, Chunk>();
    123.     }
    124.  
    125.     void InitVisibleChunks()
    126.     {
    127.         if (chunks == null)
    128.         {
    129.             return;
    130.         }
    131.         CreateChunkHolder();
    132.  
    133.         Vector3 p = viewer.position;
    134.         Vector3 ps = p / boundsSize;
    135.         Vector3Int viewerCoord = new Vector3Int(Mathf.RoundToInt(ps.x), Mathf.RoundToInt(ps.y), Mathf.RoundToInt(ps.z));
    136.  
    137.         int maxChunksInView = Mathf.CeilToInt(viewDistance / boundsSize);
    138.         float sqrViewDistance = viewDistance * viewDistance;
    139.  
    140.         // Go through all existing chunks and flag for recyling if outside of max view dst
    141.         for (int i = chunks.Count - 1; i >= 0; i--)
    142.         {
    143.             Chunk chunk = chunks[i];
    144.             Vector3 centre = CentreFromCoord(chunk.coord);
    145.             Vector3 viewerOffset = p - centre;
    146.             Vector3 o = new Vector3(Mathf.Abs(viewerOffset.x), Mathf.Abs(viewerOffset.y), Mathf.Abs(viewerOffset.z)) - Vector3.one * boundsSize / 2;
    147.             float sqrDst = new Vector3(Mathf.Max(o.x, 0), Mathf.Max(o.y, 0), Mathf.Max(o.z, 0)).sqrMagnitude;
    148.             if (sqrDst > sqrViewDistance)
    149.             {
    150.                 existingChunks.Remove(chunk.coord);
    151.                 recycleableChunks.Enqueue(chunk);
    152.                 chunks.RemoveAt(i);
    153.             }
    154.         }
    155.  
    156.         for (int x = -maxChunksInView; x <= maxChunksInView; x++)
    157.         {
    158.             for (int y = -maxChunksInView; y <= maxChunksInView; y++)
    159.             {
    160.                 for (int z = -maxChunksInView; z <= maxChunksInView; z++)
    161.                 {
    162.                     Vector3Int coord = new Vector3Int(x, y, z) + viewerCoord;
    163.  
    164.                     if (existingChunks.ContainsKey(coord))
    165.                     {
    166.                         continue;
    167.                     }
    168.  
    169.                     Vector3 centre = CentreFromCoord(coord);
    170.                     Vector3 viewerOffset = p - centre;
    171.                     Vector3 o = new Vector3(Mathf.Abs(viewerOffset.x), Mathf.Abs(viewerOffset.y), Mathf.Abs(viewerOffset.z)) - Vector3.one * boundsSize / 2;
    172.                     float sqrDst = new Vector3(Mathf.Max(o.x, 0), Mathf.Max(o.y, 0), Mathf.Max(o.z, 0)).sqrMagnitude;
    173.  
    174.                     // Chunk is within view distance and should be created (if it doesn't already exist)
    175.                     if (sqrDst <= sqrViewDistance)
    176.                     {
    177.  
    178.                         Bounds bounds = new Bounds(CentreFromCoord(coord), Vector3.one * boundsSize);
    179.                         if (IsVisibleFrom(bounds, Camera.main))
    180.                         {
    181.                             if (recycleableChunks.Count > 0)
    182.                             {
    183.                                 Chunk chunk = recycleableChunks.Dequeue();
    184.                                 chunk.coord = coord;
    185.                                 existingChunks.Add(coord, chunk);
    186.                                 chunks.Add(chunk);
    187.                                 UpdateChunkMesh(chunk);
    188.                             }
    189.                             else
    190.                             {
    191.                                 Chunk chunk = CreateChunk(coord);
    192.                                 chunk.coord = coord;
    193.                                 chunk.SetUp(mat, generateColliders);
    194.                                 existingChunks.Add(coord, chunk);
    195.                                 chunks.Add(chunk);
    196.                                 UpdateChunkMesh(chunk);
    197.                             }
    198.                         }
    199.                     }
    200.  
    201.                 }
    202.             }
    203.         }
    204.     }
    205.  
    206.     public bool IsVisibleFrom(Bounds bounds, Camera camera)
    207.     {
    208.         Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera);
    209.         return GeometryUtility.TestPlanesAABB(planes, bounds);
    210.     }
    211.  
    212.     public void UpdateChunkMesh(Chunk chunk)
    213.     {
    214.         int numVoxelsPerAxis = numPointsPerAxis - 1;
    215.         int numThreadsPerAxis = Mathf.CeilToInt(numVoxelsPerAxis / (float)threadGroupSize);
    216.         float pointSpacing = boundsSize / (numPointsPerAxis - 1);
    217.  
    218.         Vector3Int coord = chunk.coord;
    219.         Vector3 centre = CentreFromCoord(coord);
    220.  
    221.         Vector3 worldBounds = new Vector3(numChunks.x, numChunks.y, numChunks.z) * boundsSize;
    222.  
    223.         densityGenerator.Generate(pointsBuffer, numPointsPerAxis, boundsSize, worldBounds, centre, offset, pointSpacing);
    224.  
    225.         triangleBuffer.SetCounterValue(0);
    226.         shader.SetBuffer(0, "points", pointsBuffer);
    227.         shader.SetBuffer(0, "triangles", triangleBuffer);
    228.         shader.SetInt("numPointsPerAxis", numPointsPerAxis);
    229.         shader.SetFloat("isoLevel", isoLevel);
    230.  
    231.         shader.Dispatch(0, numThreadsPerAxis, numThreadsPerAxis, numThreadsPerAxis);
    232.  
    233.         // Get number of triangles in the triangle buffer
    234.         ComputeBuffer.CopyCount(triangleBuffer, triCountBuffer, 0);
    235.         int[] triCountArray = { 0 };
    236.         triCountBuffer.GetData(triCountArray);
    237.         int numTris = triCountArray[0];
    238.  
    239.         // Get triangle data from shader
    240.         Triangle[] tris = new Triangle[numTris];
    241.         triangleBuffer.GetData(tris, 0, 0, numTris);
    242.  
    243.         Mesh mesh = chunk.mesh;
    244.         mesh.Clear();
    245.  
    246.         var vertices = new Vector3[numTris * 3];
    247.         var meshTriangles = new int[numTris * 3];
    248.  
    249.         for (int i = 0; i < numTris; i++)
    250.         {
    251.             for (int j = 0; j < 3; j++)
    252.             {
    253.                 meshTriangles[i * 3 + j] = i * 3 + j;
    254.                 vertices[i * 3 + j] = tris[i][j];
    255.             }
    256.         }
    257.         mesh.vertices = vertices;
    258.         mesh.triangles = meshTriangles;
    259.  
    260.         mesh.RecalculateNormals();
    261.     }
    262.  
    263.     public void UpdateAllChunks()
    264.     {
    265.  
    266.         // Create mesh for each chunk
    267.         foreach (Chunk chunk in chunks)
    268.         {
    269.             UpdateChunkMesh(chunk);
    270.         }
    271.  
    272.     }
    273.  
    274.     void OnDestroy()
    275.     {
    276.         if (Application.isPlaying)
    277.         {
    278.             ReleaseBuffers();
    279.         }
    280.     }
    281.  
    282.     void CreateBuffers()
    283.     {
    284.         int numPoints = numPointsPerAxis * numPointsPerAxis * numPointsPerAxis;
    285.         int numVoxelsPerAxis = numPointsPerAxis - 1;
    286.         int numVoxels = numVoxelsPerAxis * numVoxelsPerAxis * numVoxelsPerAxis;
    287.         int maxTriangleCount = numVoxels * 5;
    288.  
    289.         // Always create buffers in editor (since buffers are released immediately to prevent memory leak)
    290.         // Otherwise, only create if null or if size has changed
    291.         if (!Application.isPlaying || (pointsBuffer == null || numPoints != pointsBuffer.count))
    292.         {
    293.             if (Application.isPlaying)
    294.             {
    295.                 ReleaseBuffers();
    296.             }
    297.             triangleBuffer = new ComputeBuffer(maxTriangleCount, sizeof(float) * 3 * 3, ComputeBufferType.Append);
    298.             pointsBuffer = new ComputeBuffer(numPoints, sizeof(float) * 4);
    299.             triCountBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Raw);
    300.  
    301.         }
    302.     }
    303.  
    304.     void ReleaseBuffers()
    305.     {
    306.         if (triangleBuffer != null)
    307.         {
    308.             triangleBuffer.Release();
    309.             pointsBuffer.Release();
    310.             triCountBuffer.Release();
    311.         }
    312.     }
    313.  
    314.     Vector3 CentreFromCoord(Vector3Int coord)
    315.     {
    316.         // Centre entire map at origin -- gives 0,0,0 as response for 1 chunk
    317.         if (fixedMapSize)
    318.         {
    319.             Vector3 totalBounds = (Vector3)numChunks * boundsSize;
    320.             return -totalBounds / 2 + (Vector3)coord * boundsSize + Vector3.one * boundsSize / 2;
    321.         }
    322.  
    323.         return new Vector3(coord.x, coord.y, coord.z) * boundsSize;
    324.     }
    325.  
    326.     void CreateChunkHolder()
    327.     {
    328.         // Create/find mesh holder object for organizing chunks under in the hierarchy
    329.         if (chunkHolder == null)
    330.         {
    331.             if (GameObject.Find(chunkHolderName))
    332.             {
    333.                 chunkHolder = GameObject.Find(chunkHolderName);
    334.             }
    335.             else
    336.             {
    337.                 chunkHolder = new GameObject(chunkHolderName);
    338.             }
    339.         }
    340.     }
    341.  
    342.     // Create/get references to all chunks
    343.     void InitChunks()
    344.     {
    345.         CreateChunkHolder();
    346.         chunks = new List<Chunk>();
    347.         List<Chunk> oldChunks = new List<Chunk>(FindObjectsOfType<Chunk>());
    348.      
    349.         // Go through all coords and create a chunk there if one doesn't already exist
    350.         for (int x = 0; x < numChunks.x; x++)
    351.         {
    352.             for (int y = 0; y < numChunks.y; y++)
    353.             {
    354.                 for (int z = 0; z < numChunks.z; z++)
    355.                 {
    356.                     Vector3Int coord = new Vector3Int(x, y, z);
    357.                     bool chunkAlreadyExists = false;
    358.  
    359.                     // If chunk already exists, add it to the chunks list, and remove from the old list.
    360.                     for (int i = 0; i < oldChunks.Count; i++)
    361.                     {
    362.                         if (oldChunks[i].coord == coord)
    363.                         {
    364.                             chunks.Add(oldChunks[i]);
    365.                             oldChunks.RemoveAt(i);
    366.                             chunkAlreadyExists = true;
    367.                             break;
    368.                         }
    369.                     }
    370.  
    371.                     // Create new chunk
    372.                     if (!chunkAlreadyExists)
    373.                     {
    374.                         var newChunk = CreateChunk(coord);
    375.                         chunks.Add(newChunk);
    376.                     }
    377.  
    378.                     chunks[chunks.Count - 1].SetUp(mat, generateColliders);
    379.                 }
    380.             }
    381.         }
    382.  
    383.         // Delete all unused chunks
    384.         for (int i = 0; i < oldChunks.Count; i++)
    385.         {
    386.             oldChunks[i].DestroyOrDisable();
    387.         }
    388.     }
    389.  
    390.     Chunk CreateChunk(Vector3Int coord)
    391.     {
    392.         GameObject chunk = new GameObject($"Chunk ({coord.x}, {coord.y}, {coord.z})");
    393.         chunk.transform.parent = chunkHolder.transform;
    394.         Chunk newChunk = chunk.AddComponent<Chunk>();
    395.         newChunk.coord = coord;
    396.         return newChunk;
    397.     }
    398.  
    399.     void OnValidate()
    400.     {
    401.         settingsUpdated = true;
    402.     }
    403.  
    404.     struct Triangle
    405.     {
    406. #pragma warning disable 649 // disable unassigned variable warning
    407.         public Vector3 a;
    408.         public Vector3 b;
    409.         public Vector3 c;
    410.  
    411.         public Vector3 this[int i]
    412.         {
    413.             get
    414.             {
    415.                 switch (i)
    416.                 {
    417.                     case 0:
    418.                         return a;
    419.                     case 1:
    420.                         return b;
    421.                     default:
    422.                         return c;
    423.                 }
    424.             }
    425.         }
    426.     }
    427.  
    428.     void OnDrawGizmos()
    429.     {
    430.         if (showBoundsGizmo)
    431.         {
    432.             Gizmos.color = boundsGizmoCol;
    433.  
    434.             List<Chunk> chunks = (this.chunks == null) ? new List<Chunk>(FindObjectsOfType<Chunk>()) : this.chunks;
    435.             foreach (var chunk in chunks)
    436.             {
    437.                 Bounds bounds = new Bounds(CentreFromCoord(chunk.coord), Vector3.one * boundsSize);
    438.                 Gizmos.color = boundsGizmoCol;
    439.                 Gizmos.DrawWireCube(CentreFromCoord(chunk.coord), Vector3.one * boundsSize);
    440.             }
    441.         }
    442.     }
    443.  
    444. }
     
  7. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,346
    That's a lot of code! Hard to know where to start.
     
  8. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
    @Baste agreed - apologies.If we look back at this dig function, this is the bit where i try to determine which triangle was hit by the collider :

    Code (CSharp):
    1. MeshCollider meshCollider = hit.collider as MeshCollider;
    2.             if (meshCollider == null || meshCollider.sharedMesh == null)
    3.                 return;
    4.  
    5.          
    6.             Mesh mesh = meshCollider.sharedMesh;
    7.             Vector3[] vertices = mesh.vertices;
    8.             int[] triangles = mesh.triangles;
    9.             Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
    10.             Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
    11.             Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
    12.             Transform hitTransform = hit.collider.transform;
    It grabs the hit collider as a meshCollider - gets the shared mesh.

    Gets that mesh vertices, gets the triangles, and then uses the hit.triangleIndex to find the 3 points that have been hit. I assume this is where the problem is - probably in my logic I am doing something wrong?

    The sharedMesh that is returned, is equal to the mesh which is generated in the MeshGenerator class I pasted in the previous post for context :)
     
  9. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,346
    Dig() looks fine, tbh. The only issue is that you're drawing the lines for 1000 seconds, so it might just be that you're looking at old results.

    To debug this properly; first I'd copy p0, p1, and p2 (after you transform them) to fields, and draw them in OnDrawGizmos with Gizmos.DrawLine, at least until you've got it right. Then you'll only be looking at a single triangle at a time.

    After that, I'd reduce the mesh to only a single triangle, and then keep adding them one at a time. In fact, run your algorithm on a normal quad, see if you get it working there first. Running it on top of the generated mesh makes it hard to tell where the issue lies.
     
    TheSituation likes this.
  10. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
    Okay @Baste - good idea.

    So I added a quad, rotated it by 90 degrees on the x axis so i could stand on it.

    Clicked, boom - it highlights the triangle I would expect! Great!



    My updated code is as you requested - moved the draw line into Gizmos(not sure why that is an important step but regardless it works) new code here:

    Code (CSharp):
    1. Vector3 p0, p1, p2;
    2.     Boolean drawGizmosReady = false;
    3.     void Dig()
    4.     {
    5.         Ray ray = new Ray(myEyes.transform.position, myEyes.transform.forward);
    6.         Debug.DrawRay(ray.origin, ray.direction * 50f, Color.cyan, 20f) ;
    7.         RaycastHit hit;
    8.  
    9.         int layerMaskGround = 1 << LayerMask.NameToLayer("Ground");
    10.          if(Physics.Raycast(ray, out hit,1000f, layerMaskGround)) //-- this dos not work - debug line shows ray is hitting layer 8 == ground but with the mask, nothing is hit?
    11.         //if (Physics.Raycast(ray,out hit, 50f))
    12.         {
    13.  
    14.             //remove a 'spades' worth of voxels, if pointing at the terrain, and shove them somewhere random nearby.
    15.             Debug.Log("Tag is:" + hit.collider.gameObject.tag + " and object name is:" + hit.collider.gameObject.name + "And layer is:" + hit.collider.gameObject.layer);
    16.  
    17.  
    18.             MeshCollider meshCollider = hit.collider as MeshCollider;
    19.             if (meshCollider == null || meshCollider.sharedMesh == null)
    20.                 return;
    21.  
    22.            
    23.             Mesh mesh = meshCollider.sharedMesh;
    24.             Vector3[] vertices = mesh.vertices;
    25.             int[] triangles = mesh.triangles;
    26.             drawGizmosReady = false;
    27.             p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
    28.             p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
    29.             p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
    30.             Transform hitTransform = hit.collider.transform;
    31.          
    32.             p0 = hitTransform.TransformPoint(p0);
    33.             p1 = hitTransform.TransformPoint(p1);
    34.             p2 = hitTransform.TransformPoint(p2);
    35.             drawGizmosReady = true;
    36.            // Debug.DrawLine(p0, p1,Color.red,1000f);
    37.            // Debug.DrawLine(p1, p2, Color.red, 1000f);
    38.            // Debug.DrawLine(p2, p0, Color.red, 1000f);
    39.  
    40.  
    41.         }
    42.         else{
    43.             Debug.Log("Hit nothing");
    44.         }
    45.     }
    46.  
    47.  
    48.     void OnDrawGizmos()
    49.     {
    50.         // Draw a yellow sphere at the transform's position
    51.  
    52.         if (drawGizmosReady)
    53.         {
    54.             Gizmos.color = Color.yellow;
    55.             Gizmos.DrawLine(p0, p1);
    56.             Gizmos.DrawLine(p1, p2);
    57.             Gizmos.DrawLine(p2, p0);
    58.             Gizmos.DrawSphere(transform.position, 1);
    59.         }
    60.     }
    So you now suggest running the algorithm to generate my mesh with only one triangle, and work on it from there. I like the idea, but looking at my mesh generator, im not sure how to restrict it to 1 triangle? I used the MeshGenerator code from somebody's tutorial and it worked (up until now so I dont understand it intricately).

    To me I think I would limit something in the MeshGenerator around :

    Code (CSharp):
    1.  densityGenerator.Generate(pointsBuffer, numPointsPerAxis, boundsSize, worldBounds, centre, offset, pointSpacing);
    2.  
    3.         triangleBuffer.SetCounterValue(0);
    4.         shader.SetBuffer(0, "points", pointsBuffer);
    5.         shader.SetBuffer(0, "triangles", triangleBuffer);
    6.         shader.SetInt("numPointsPerAxis", numPointsPerAxis);
    7.         shader.SetFloat("isoLevel", isoLevel);
    8.  
    9.         shader.Dispatch(0, numThreadsPerAxis, numThreadsPerAxis, numThreadsPerAxis);
    10.  
    11.         // Get number of triangles in the triangle buffer
    12.         ComputeBuffer.CopyCount(triangleBuffer, triCountBuffer, 0);
    13.         int[] triCountArray = { 0 };
    14.         triCountBuffer.GetData(triCountArray);
    15.         int numTris = triCountArray[0];
    16.  
    17.         // Get triangle data from shader
    18.         Triangle[] tris = new Triangle[numTris];
    19.         triangleBuffer.GetData(tris, 0, 0, numTris);
    20.  
    21.         Mesh mesh = chunk.mesh;
    Thanks again @Baste your help is very much appreciated!
     
  11. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,346
    It's not strictly important, but the idea is to only draw a single triangle at a time, and not draw it when you're not looking at something, as that makes you sure that the code's doing what you expect. For that i'd set
    drawGizmosReady to false if your raycast doesn't hit anything.

    To reduce the size, well, if you don't understand the code, I'd just play with the variables exposed. I'm guessing that reducing numPointsPerAxis to the minimum value (2) should reduce the complexity a bunch.
     
  12. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
    Okay @Baste some great news!

    Reducing the numPointsPerAxis to 2, as you suggested, has broken my mesh into 2 large triangles, and collision works perfectly like that:



    Putting number of tris to 3 appears to work at first...:



    but then I click a run it a 2nd, 3rd and 4th time and these are the results:



    Another run:



    Therefore, the problem appears when it is as simple as 3 points per axis.

    Going to try some debugging from here...but thoughts and pointers more than welcome.

    Okay so debugging I can't see why its not working. I also don't necessarily understand all of what is happening. For example, I don't know why we do this :


    Code (CSharp):
    1.   p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
    2.             p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
    3.             p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
    Why do we go into the triangles array and get our index, then multiply it by 3?

    I continued to debug, and thought, why don't I draw all the triangles on my mesh? So I added a bit of code in the MeshGenerator to do that, just to validate that the collision triangle at least matches a triangle on my mesh:

     
    Last edited: Jun 22, 2020
  13. TheSituation

    TheSituation

    Joined:
    Apr 17, 2014
    Posts:
    23
  14. zphensley42

    zphensley42

    Joined:
    Jan 31, 2021
    Posts:
    1
    So, I am working on something similar. I think a key point here is how the mesh is treated vs how the raycast triangleIndex is generated. Raycast hit is acting on the MeshCollider, but that collider uses the sharedMesh (stored) to generate the triangles. If you are attempting to match this up with a generated mesh that is not stored back *out* to that sharedMesh, then the triangle indices won't match up.

    In my example, I have a mesh that I iterate through and split normal-positive faces into submeshes for selection. This works and I can index the triangles myself and see what I expect. If I try to match these up with raycast collision, the triangleIndex matches in the sharedMesh, but the triangles *of* the sharedMesh do not match with the order of the triangles in my submesh version of the mesh instance. Thus, I cannot rely on the index this way.



    Left list is sharedMesh triangles, right list is mesh triangles. Top is triangle index, but that index only works on the left list as I expect it to.


    UPDATE:

    Just change the MeshCollider to solve the above:
    Code (CSharp):
    1.         splitMesh ();
    2.         meshCollider.sharedMesh = mesh;
     
    Last edited: Feb 6, 2021