55 lines
1.7 KiB
C#
55 lines
1.7 KiB
C#
using System;
|
|
|
|
using Microsoft.Xna.Framework;
|
|
|
|
namespace Syntriax.Engine.Physics2D.Primitives;
|
|
|
|
public record Triangle(Vector2 A, Vector2 B, Vector2 C)
|
|
{
|
|
public float Area => MathF.Abs((
|
|
A.X * (B.Y - C.Y) +
|
|
B.X * (C.Y - A.Y) +
|
|
C.X * (A.Y - B.Y)
|
|
) * .5f);
|
|
|
|
public Circle CircumCircle
|
|
{
|
|
get
|
|
{
|
|
Vector2 midAB = (A + B) / 2;
|
|
Vector2 midBC = (B + C) / 2;
|
|
|
|
float slopeAB = (B.Y - A.Y) / (B.X - A.X);
|
|
float slopeBC = (C.Y - B.Y) / (C.X - B.X);
|
|
|
|
Vector2 center;
|
|
if (MathF.Abs(slopeAB - slopeBC) > float.Epsilon)
|
|
{
|
|
float x = (slopeAB * slopeBC * (A.Y - C.Y) + slopeBC * (A.X + B.X) - slopeAB * (B.X + C.X)) / (2 * (slopeBC - slopeAB));
|
|
float y = -(x - (A.X + B.X) / 2) / slopeAB + (A.Y + B.Y) / 2;
|
|
center = new Vector2(x, y);
|
|
}
|
|
else
|
|
center = (midAB + midBC) * .5f;
|
|
|
|
return new(center, Vector2.Distance(center, A));
|
|
}
|
|
}
|
|
|
|
public bool Overlaps(Vector2 point)
|
|
{
|
|
float originalTriangleArea = Area;
|
|
|
|
float pointTriangleArea1 = new Triangle(point, B, C).Area;
|
|
float pointTriangleArea2 = new Triangle(A, point, C).Area;
|
|
float pointTriangleArea3 = new Triangle(A, B, point).Area;
|
|
|
|
float pointTriangleAreasSum = pointTriangleArea1 + pointTriangleArea2 + pointTriangleArea3;
|
|
|
|
return originalTriangleArea.ApproximatelyEquals(pointTriangleAreasSum, float.Epsilon * 3f);
|
|
}
|
|
|
|
public bool ApproximatelyEquals(Triangle other)
|
|
=> A.ApproximatelyEquals(other.A) && B.ApproximatelyEquals(other.B) && C.ApproximatelyEquals(other.C);
|
|
}
|