Skip to content

Instantly share code, notes, and snippets.

@Hyperparticle
Created November 28, 2017 17:36
Show Gist options
  • Save Hyperparticle/02c9b6cf805335d029be85e0a4a3f8cd to your computer and use it in GitHub Desktop.
Save Hyperparticle/02c9b6cf805335d029be85e0a4a3f8cd to your computer and use it in GitHub Desktop.
Triangle Prefab Script
public class DrawTriangle : DrawShape
{
// ...
private PolygonCollider2D _polygonCollider2D;
// Triangle vertices (in absolute coordinates)
private readonly List<Vector2> _vertices = new List<Vector2>(3);
public override bool ShapeFinished { get { return _vertices.Count >= 3; } }
// ...
private void Awake()
{
// ...
_polygonCollider2D = GetComponent<PolygonCollider2D>();
}
// ...
public override void UpdateShape(Vector2 newVertex)
{
if (_vertices.Count < 2) {
return;
}
_vertices[_vertices.Count - 1] = newVertex;
// Set the gameobject's position to be the center of mass
var center = _vertices.Centroid();
transform.position = center;
// Update the mesh relative to the transform
var relativeVertices = _vertices.Select(v => v - center).ToArray();
_meshFilter.mesh = PolygonMesh(relativeVertices, FillColor);
// ...
// Update the collider
_polygonCollider2D.points = relativeVertices;
}
/// <summary>
/// Creates and returns a polygon mesh given a list of its vertices.
/// </summary>
private static Mesh PolygonMesh(Vector2[] vertices, Color fillColor)
{
// Find all the triangles in the shape
var triangles = new Triangulator(vertices).Triangulate();
// Assign each vertex the fill color
var colors = Enumerable.Repeat(fillColor, vertices.Length).ToArray();
var mesh = new Mesh {
name = "Triangle",
vertices = vertices.ToVector3(),
triangles = triangles,
colors = colors
};
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return mesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment