Syntriax.Engine/Engine.Physics2D/Physics2D.cs

75 lines
2.9 KiB
C#

using System;
using Syntriax.Engine.Core;
using Syntriax.Engine.Physics2D;
using Syntriax.Engine.Physics2D.Primitives;
namespace Engine.Physics2D;
public static partial class Physics2D
{
public static bool Overlaps(this Circle left, Circle right)
{
float distanceSquared = left.Center.FromTo(right.Center).LengthSquared();
float radiusSumSquared = left.RadiusSquared + right.RadiusSquared;
return distanceSquared < radiusSumSquared;
}
public static bool Overlaps(this Circle left, Circle right, out Vector2D normal, out float depth)
{
Vector2D distanceVector = left.Center.FromTo(right.Center);
float distanceSquared = distanceVector.LengthSquared();
float radiusSumSquared = left.RadiusSquared + right.RadiusSquared;
bool isOverlapping = distanceSquared < radiusSumSquared;
depth = 0f;
normal = distanceVector.Normalized;
if (isOverlapping)
depth = MathF.Sqrt(radiusSumSquared - distanceSquared);
return isOverlapping;
}
public static bool Overlaps(this Circle circle, Vector2D point) => circle.Center.FromTo(point).LengthSquared() <= circle.RadiusSquared;
public static bool Overlaps(this Circle circle, Vector2D point, out Vector2D normal, out float depth)
{
Vector2D distanceVector = circle.Center.FromTo(point);
float distanceSquared = distanceVector.LengthSquared();
float radiusSquared = circle.RadiusSquared;
bool isOverlapping = distanceSquared < radiusSquared;
depth = 0f;
normal = distanceVector.Normalized;
if (isOverlapping)
depth = MathF.Sqrt(radiusSquared - distanceSquared);
return isOverlapping;
}
public static bool Overlaps(this AABB aabb, Vector2D point)
=> point.X >= aabb.LowerBoundary.X && point.X <= aabb.UpperBoundary.X &&
point.Y >= aabb.LowerBoundary.Y && point.Y <= aabb.UpperBoundary.Y;
public static bool Overlaps(this AABB left, AABB right)
=> left.LowerBoundary.X <= right.UpperBoundary.X && left.UpperBoundary.X >= right.LowerBoundary.X &&
left.LowerBoundary.Y <= right.UpperBoundary.Y && left.UpperBoundary.Y >= right.LowerBoundary.Y;
public static bool Overlaps(Triangle triangle, Vector2D point)
{
float originalTriangleArea = triangle.Area;
float pointTriangleArea1 = new Triangle(point, triangle.B, triangle.C).Area;
float pointTriangleArea2 = new Triangle(triangle.A, point, triangle.C).Area;
float pointTriangleArea3 = new Triangle(triangle.A, triangle.B, point).Area;
float pointTriangleAreasSum = pointTriangleArea1 + pointTriangleArea2 + pointTriangleArea3;
return originalTriangleArea.ApproximatelyEquals(pointTriangleAreasSum, float.Epsilon * 3f);
}
public static bool LaysOn(this Vector2D point, Line line) => Line.Intersects(line, point);
}