Engine-Pong/Game/Physics2D/PhysicsEngine2D.cs

80 lines
2.3 KiB
C#
Raw Normal View History

2023-11-30 17:52:09 +03:00
using System;
using System.Collections.Generic;
2023-12-05 17:39:38 +03:00
2024-01-23 12:16:58 +03:00
using Syntriax.Engine.Core;
2023-11-30 17:52:09 +03:00
using Syntriax.Engine.Core.Abstract;
using Syntriax.Engine.Physics2D.Abstract;
2023-12-07 10:55:49 +03:00
using Syntriax.Engine.Physics2D.Primitives;
2023-11-30 17:52:09 +03:00
namespace Syntriax.Engine.Physics2D;
public class PhysicsEngine2D : IPhysicsEngine2D
{
2023-12-06 13:25:16 +03:00
private List<IRigidBody2D> rigidBodies = new List<IRigidBody2D>(32);
private List<ICollider2D> colliders = new List<ICollider2D>(64);
2023-11-30 17:52:09 +03:00
private int _iterationCount = 1;
public int IterationCount { get => _iterationCount; set => _iterationCount = value < 1 ? 1 : value; }
public void AddRigidBody(IRigidBody2D rigidBody)
{
if (rigidBodies.Contains(rigidBody))
return;
rigidBodies.Add(rigidBody);
foreach (var collider2D in rigidBody.BehaviourController.GetBehaviours<ICollider2D>())
colliders.Add(collider2D);
rigidBody.BehaviourController.OnBehaviourAdded += OnBehaviourAdded;
rigidBody.BehaviourController.OnBehaviourRemoved += OnBehaviourRemoved;
}
public void RemoveRigidBody(IRigidBody2D rigidBody)
{
rigidBodies.Remove(rigidBody);
}
2023-12-06 15:56:46 +03:00
private List<Line> lines = new List<Line>(32);
2023-12-06 14:14:55 +03:00
2023-11-30 17:52:09 +03:00
public void Step(float deltaTime)
{
float intervalDeltaTime = deltaTime / IterationCount;
2023-12-05 17:55:38 +03:00
for (int iterationIndex = 0; iterationIndex < IterationCount; iterationIndex++)
2023-11-30 17:52:09 +03:00
{
foreach (var rigidBody in rigidBodies)
2023-12-04 23:55:43 +03:00
StepRigidBody(rigidBody, intervalDeltaTime);
2023-11-30 17:52:09 +03:00
2023-12-01 17:42:07 +03:00
foreach (var collider in colliders)
2023-12-05 17:39:38 +03:00
collider.Recalculate();
2023-11-30 17:52:09 +03:00
}
}
2023-12-06 13:25:16 +03:00
private void StepRigidBody(IRigidBody2D rigidBody, float intervalDeltaTime)
2023-12-04 23:55:43 +03:00
{
2024-01-23 12:16:58 +03:00
Vector2D nextPosition = rigidBody.Transform.Position;
2023-12-04 23:55:43 +03:00
nextPosition += rigidBody.Velocity * intervalDeltaTime;
rigidBody.Transform.Position = nextPosition;
}
2023-11-30 17:52:09 +03:00
private void OnBehaviourAdded(IBehaviourController controller, IBehaviour behaviour)
{
if (behaviour is not ICollider2D collider2D)
return;
colliders.Add(collider2D);
}
private void OnBehaviourRemoved(IBehaviourController controller, IBehaviour behaviour)
{
if (behaviour is not ICollider2D collider2D)
return;
colliders.Remove(collider2D);
}
}