servicepoint-tanks/tanks-backend/TanksServer/GameLogic/MoveBullets.cs

57 lines
1.8 KiB
C#
Raw Normal View History

2024-04-10 19:25:45 +02:00
namespace TanksServer.GameLogic;
2024-04-07 19:52:16 +02:00
2024-04-29 21:52:50 +02:00
internal sealed class MoveBullets(
MapEntityManager entityManager,
IOptions<GameRules> options
) : ITickStep
2024-04-07 19:52:16 +02:00
{
2024-04-29 21:52:50 +02:00
private readonly double _smartBulletInertia = options.Value.SmartBulletInertia;
2024-04-28 15:34:32 +02:00
public ValueTask TickAsync(TimeSpan delta)
2024-04-07 19:52:16 +02:00
{
2024-04-17 19:34:19 +02:00
foreach (var bullet in entityManager.Bullets)
2024-04-16 19:40:08 +02:00
MoveBullet(bullet, delta);
2024-04-07 19:52:16 +02:00
2024-04-28 15:34:32 +02:00
return ValueTask.CompletedTask;
2024-04-07 19:52:16 +02:00
}
2024-04-29 21:52:50 +02:00
private void MoveBullet(Bullet bullet, TimeSpan delta)
2024-04-07 19:52:16 +02:00
{
if (bullet.Stats.Smart && TryGetSmartRotation(bullet.Position, bullet.Owner, out var wantedRotation))
2024-04-29 21:52:50 +02:00
{
var inertiaFactor = _smartBulletInertia * delta.TotalSeconds;
var difference = wantedRotation - bullet.Rotation;
bullet.Rotation += difference * inertiaFactor;
}
2024-05-08 01:16:18 +02:00
bullet.Speed += (bullet.Stats.Acceleration * delta.TotalSeconds);
2024-04-29 16:59:37 +02:00
var speed = bullet.Speed * delta.TotalSeconds;
2024-04-12 18:32:10 +02:00
var angle = bullet.Rotation * 2 * Math.PI;
2024-04-07 19:52:16 +02:00
bullet.Position = new FloatPosition(
2024-04-16 19:40:08 +02:00
bullet.Position.X + Math.Sin(angle) * speed,
bullet.Position.Y - Math.Cos(angle) * speed
2024-04-07 19:52:16 +02:00
);
}
2024-04-29 21:52:50 +02:00
private bool TryGetSmartRotation(FloatPosition position, Player bulletOwner, out double rotation)
{
var nearestEnemy = entityManager.Tanks
.Where(t => t.Owner != bulletOwner)
.MinBy(t => position.Distance(t.Position));
if (nearestEnemy == null)
{
rotation = double.NaN;
return false;
}
var rotationRadians = Math.Atan2(
y: nearestEnemy.Position.Y - position.Y,
x: nearestEnemy.Position.X - position.X
) + (Math.PI / 2);
rotation = rotationRadians / (2 * Math.PI);
return true;
}
2024-04-13 14:08:51 +02:00
}