76 lines
2.2 KiB
C#
76 lines
2.2 KiB
C#
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
|
||
|
using Syntriax.Engine.Core;
|
||
|
using Syntriax.Engine.Core.Abstract;
|
||
|
using Syntriax.Engine.Physics2D.Abstract;
|
||
|
using Syntriax.Engine.Physics2D.Primitives;
|
||
|
|
||
|
namespace Syntriax.Engine.Physics2D;
|
||
|
|
||
|
public class PhysicsEngine2D : IPhysicsEngine2D
|
||
|
{
|
||
|
private List<IRigidBody2D> rigidBodies = new List<IRigidBody2D>(32);
|
||
|
private List<ICollider2D> colliders = new List<ICollider2D>(64);
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
|
||
|
public void Step(float deltaTime)
|
||
|
{
|
||
|
float intervalDeltaTime = deltaTime / IterationCount;
|
||
|
|
||
|
for (int iterationIndex = 0; iterationIndex < IterationCount; iterationIndex++)
|
||
|
{
|
||
|
foreach (var rigidBody in rigidBodies)
|
||
|
StepRigidBody(rigidBody, intervalDeltaTime);
|
||
|
|
||
|
foreach (var collider in colliders)
|
||
|
collider.Recalculate();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private static void StepRigidBody(IRigidBody2D rigidBody, float intervalDeltaTime)
|
||
|
{
|
||
|
rigidBody.Transform.Position += rigidBody.Velocity * intervalDeltaTime;
|
||
|
rigidBody.Transform.Rotation += rigidBody.AngularVelocity * intervalDeltaTime;
|
||
|
}
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
}
|