Hello folks.
I’m trying to select some regions in a mesh. To do that I’m using raycasts, so I create some functions down bellow.
The region that are not selected in gif the raycast return the hit.triangleIndex -1. The raycast detect the mesh, and return the value, so I’ve no idea what’s happen in this situation.
I create a simple model in blender to simulate concave and convex surface and it works like a charm.
Also I check all triangles in the mesh.triangles and they are right.
The code is working pretty fine.
Get mouse position
private HashSet<int> _currentSelection = new HashSet<int>();
private Vector2 _mouseOrigin;
void update()
{
if (Input.GetMouseButton(1))
{
_mouseOrigin = _cam.ScreenToWorldPoint(Input.mousePosition);
BrushSelection();
}
if (_currentSelection != null)
{
foreach(var index in _currentSelection)
{
MarkTrianglebyIndex(index);
}
}
}
A square brush of raycasts
private void BrushSelection()
{
Vector2 p1 = new Vector2(_mouseOrigin.x + _burshOffSet, _mouseOrigin.y + _burshOffSet);
Vector2 p2 = new Vector2(_mouseOrigin.x - _burshOffSet, _mouseOrigin.y - _burshOffSet);
for (float x = p2.x; x < p1.x; x += 0.005f)
{
for (float y = p2.y; y < p1.y; y += 0.005f)
{
var raycastOffSet = -0.5f;
Vector3 raycastPosition = new Vector3(x, y, raycastOffSet);
RaycastHit hit;
Ray ray = new Ray(raycastPosition, _cam.transform.forward);
Physics.queriesHitBackfaces = true;
if (Physics.Raycast(ray, out hit, _playerLayer))
{
if (hit.triangleIndex > 0)
{
_currentSelection.Add(hit.triangleIndex);
}
}
Debug.DrawRay(ray.origin, ray.direction, Color.cyan);
}
}
}
Show in the editor selected indexes
private void MarkTrianglebyIndex(int index)
{
Vector3 p0 = transform.TransformPoint(_meshVertices[_meshTriangles[index * 3 + 0]]);
Vector3 p1 = transform.TransformPoint(_meshVertices[_meshTriangles[index * 3 + 1]]);
Vector3 p2 = transform.TransformPoint(_meshVertices[_meshTriangles[index * 3 + 2]]);
Debug.DrawLine(p0, p1, Color.red);
Debug.DrawLine(p1, p2, Color.red);
Debug.DrawLine(p2, p0, Color.red);
}