Created
January 17, 2016 12:21
-
-
Save x5lcfd/eb35e80906b5c73f5f9f to your computer and use it in GitHub Desktop.
Draw a polygon in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using UnityEngine.Sprites; | |
using System; | |
using System.Collections.Generic; | |
public class DrawPolygon : Graphic | |
{ | |
[SerializeField] | |
private Sprite m_sprite; | |
private int m_nSides = 3; | |
public int nSides | |
{ | |
get { return m_nSides; } | |
set { m_nSides = value; } | |
} | |
private List<float> m_coefficients = new List<float>() { 1.0f, 1.0f, 1.0f }; | |
public List<float> coefficients | |
{ | |
get { return m_coefficients; } | |
} | |
public Sprite sprite { get { return m_sprite; } } | |
protected override void OnEnable() | |
{ | |
base.OnEnable(); | |
} | |
/// Image's dimensions used for drawing. X = left, Y = bottom, Z = right, W = top. | |
private Vector4 GetDrawingDimensions() | |
{ | |
var padding = DataUtility.GetPadding(sprite); | |
var size = new Vector2(sprite.rect.width, sprite.rect.height); | |
Rect r = GetPixelAdjustedRect(); | |
int spriteW = Mathf.RoundToInt(size.x); | |
int spriteH = Mathf.RoundToInt(size.y); | |
var v = new Vector4( | |
padding.x / spriteW, | |
padding.y / spriteH, | |
(spriteW - padding.z) / spriteW, | |
(spriteH - padding.w) / spriteH); | |
v = new Vector4( | |
r.x + r.width * v.x, | |
r.y + r.height * v.y, | |
r.x + r.width * v.z, | |
r.y + r.height * v.w | |
); | |
return v; | |
} | |
protected override void OnPopulateMesh(VertexHelper vh) | |
{ | |
base.OnPopulateMesh(vh); | |
var v = GetDrawingDimensions(); | |
// var uv = DataUtility.GetOuterUV(sprite); | |
var halfHeight = Mathf.Abs(v.y); | |
var color32 = color; | |
vh.Clear(); | |
vh.AddVert(new Vector3(0.0f, 0.0f), color32, Vector2.zero); | |
for (int i = 0; i < nSides; i++) | |
{ | |
var angle = Mathf.PI / 2 - 2 * Mathf.PI / nSides * i; | |
vh.AddVert( | |
new Vector3(Mathf.Sin(angle) * halfHeight * coefficients[i], Mathf.Cos(angle) * halfHeight * coefficients[i]), | |
color32, Vector2.zero); | |
} | |
for (int i = 0; i < nSides - 2; i++) | |
{ | |
vh.AddTriangle(0, (i + 1) % nSides, (i + 2) % nSides); | |
} | |
vh.AddTriangle(0, nSides - 1, nSides); | |
vh.AddTriangle(0, nSides, 1); | |
} | |
public Vector3 GetActualPosition() | |
{ | |
return Vector3.zero; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment