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;
2024-01-23 12:16:58 +03:00
using Syntriax.Engine.Core;
2023-12-07 10:55:49 +03:00
namespace Syntriax.Engine.Physics2D.Primitives;
2024-01-23 12:16:58 +03:00
public record Triangle(Vector2D A, Vector2D B, Vector2D C)
2023-12-07 10:55:49 +03:00
{
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
{
2024-01-23 12:16:58 +03:00
Vector2D midAB = (A + B) / 2;
Vector2D midBC = (B + C) / 2;
2023-12-07 10:55:49 +03:00
float slopeAB = (B.Y - A.Y) / (B.X - A.X);
float slopeBC = (C.Y - B.Y) / (C.X - B.X);
2024-01-23 12:16:58 +03:00
Vector2D 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;
2024-01-23 12:16:58 +03:00
center = new Vector2D(x, y);
2023-12-07 10:55:49 +03:00
}
else
center = (midAB + midBC) * .5f;
2024-01-23 12:16:58 +03:00
return new(center, Vector2D.Distance(center, A));
2023-12-07 10:55:49 +03:00
}
}
2024-01-23 12:16:58 +03:00
public bool Overlaps(Vector2D point)
2023-12-07 10:55:49 +03:00
{
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
}