Engine-Pong/Game/Physics2D/Primitives/Triangle.cs

55 lines
1.7 KiB
C#
Raw Normal View History

2023-12-07 10:55:49 +03:00
using System;
using Microsoft.Xna.Framework;
namespace Syntriax.Engine.Physics2D.Primitives;
public record Triangle(Vector2 A, Vector2 B, Vector2 C)
{
2024-01-22 18:46:51 +03:00
public float Area => MathF.Abs((
2023-12-07 10:55:49 +03:00
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;
2024-01-22 18:46:51 +03:00
if (MathF.Abs(slopeAB - slopeBC) > float.Epsilon)
2023-12-07 10:55:49 +03:00
{
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;
2023-12-07 11:14:18 +03:00
center = new Vector2(x, y);
2023-12-07 10:55:49 +03:00
}
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;
2023-12-07 11:14:18 +03:00
return originalTriangleArea.ApproximatelyEquals(pointTriangleAreasSum, float.Epsilon * 3f);
2023-12-07 10:55:49 +03:00
}
2023-12-07 11:14:18 +03:00
public bool ApproximatelyEquals(Triangle other)
=> A.ApproximatelyEquals(other.A) && B.ApproximatelyEquals(other.B) && C.ApproximatelyEquals(other.C);
2023-12-07 10:55:49 +03:00
}