Search code examples
unity-game-engine2dcollider

paint polygon collider during gameplay


I'm working on a 2D game in which some objects have a triangular vision, done with a polygon colliderenter image description here

Is it possible to paint this collider so that it is visible during the gameplay?

enter image description here


Solution

  • Assuming your mean PolygonCollider2D and that it always has 3 points in the correct order I guess you could do something like

    using System.Linq;
    
    ...
    
    [RequireComponent(typeof(MeshRenderer), typeof(MeshFilter), typeof(PolygonCollider2D))]
    public class MeshCreator : MonoBehaviour
    {
        void Awake ()
        {
            var points = GetComponent<PolygonCollider2D>().points;
            var meshFilter = GetComponent<MeshFilter>();
            var mesh = new Mesh();
    
            // Just a shorthand for something like 
            //var list = new List<Vector3>();
            //foreach(var p in points)
            //{
            //    list.Add(p);
            //}
            //mesh.vertices = list.ToArray();
            mesh.vertices = points.Select(p -> (Vector3) p).ToArray();
    
            // Here create two triangles (each 3 vertices)
            // just because I don't know if you have the points in the correct order
            mesh.triangles = new int[]{0,1,2,0,2,1};
    
            meshFilter.mesh = mesh;
        }
    }
    

    and put this component next to the PolygonCollider2D. It will then replace this Object's mesh with the triangle.

    The material you can already set beforehand in the MeshRenderer.

    For getting this overlap area the simplest solution would be Semi-Transparent materials. Otherwise you might need a special shader.