Skip to content

Commit 35f52fc

Browse files
committed
Triangle2D
1 parent 184c4b8 commit 35f52fc

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
using UnityEngine;
2+
using UCL;
3+
4+
// if you need to run collision checks within a triangular area, the easiest
5+
// way to do that in Unity is to use a polygon collider. this is not very
6+
// performant. this class allows you to run those collision checks without
7+
// the performance overhead.
8+
9+
public class Triangle2D
10+
{
11+
Vector2[] vertices = new Vector2[3];
12+
13+
public Triangle2D(Vector2 v1, Vector2 v2, Vector2 v3) {
14+
Update(v1, v2, v3);
15+
}
16+
17+
// update triangle by defining all its vertices
18+
public void Update(Vector2 v1, Vector2 v2, Vector2 v3) {
19+
vertices[0] = v1;
20+
vertices[1] = v2;
21+
vertices[2] = v3;
22+
}
23+
24+
// update triangle by redefining its origin (remaining points update relative to that)
25+
public void Update(Vector2 v1) {
26+
Vector2 delta = v1 - vertices[0];
27+
vertices[0] = v1;
28+
vertices[1] += delta;
29+
vertices[2] += delta;
30+
}
31+
32+
// update triangle with rotation and pivot point
33+
public void Update(Vector2 v1, Vector2 v2, Vector2 v3, float rotation, Vector2 pivot) {
34+
vertices[0] = v1.Rotate(rotation, pivot);
35+
vertices[1] = v2.Rotate(rotation, pivot);
36+
vertices[2] = v3.Rotate(rotation, pivot);
37+
}
38+
39+
float Sign(Vector2 p1, Vector2 p2, Vector2 p3) {
40+
return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
41+
}
42+
43+
public bool Contains(Vector2 pt, bool debug = false) {
44+
float d1, d2, d3;
45+
bool has_neg, has_pos;
46+
47+
d1 = Sign(pt, vertices[0], vertices[1]);
48+
d2 = Sign(pt, vertices[1], vertices[2]);
49+
d3 = Sign(pt, vertices[2], vertices[0]);
50+
51+
has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
52+
has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
53+
54+
bool contains = ! (has_neg && has_pos);
55+
56+
return contains;
57+
}
58+
}

Assets/Scripts/2D/Geometry/Triangle2D.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)