From 786c974a23d88a2290e306b16f02733a28e2dea6 Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Tue, 16 Apr 2024 20:24:29 +0200 Subject: [PATCH] spawn bullet closer to tank --- TanksServer/GameLogic/BulletManager.cs | 3 ++- TanksServer/GameLogic/ShootFromTanks.cs | 21 ++++++++++++++++++--- TanksServer/Models/PositionHelpers.cs | 2 +- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/TanksServer/GameLogic/BulletManager.cs b/TanksServer/GameLogic/BulletManager.cs index 00d7e74..47fd579 100644 --- a/TanksServer/GameLogic/BulletManager.cs +++ b/TanksServer/GameLogic/BulletManager.cs @@ -4,7 +4,8 @@ internal sealed class BulletManager { private readonly HashSet _bullets = []; - public void Spawn(Bullet bullet) => _bullets.Add(bullet); + public void Spawn(Player tankOwner, FloatPosition position, double rotation) + => _bullets.Add(new Bullet(tankOwner, position, rotation)); public IEnumerable GetAll() => _bullets; diff --git a/TanksServer/GameLogic/ShootFromTanks.cs b/TanksServer/GameLogic/ShootFromTanks.cs index ade1975..ea33921 100644 --- a/TanksServer/GameLogic/ShootFromTanks.cs +++ b/TanksServer/GameLogic/ShootFromTanks.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + namespace TanksServer.GameLogic; internal sealed class ShootFromTanks( @@ -27,11 +29,24 @@ internal sealed class ShootFromTanks( var rotation = tank.Orientation / 16d; var angle = rotation * 2d * Math.PI; + + /* TODO: when standing next to a wall, the bullet sometimes misses the first pixel. + Spawning the bullet to close to the tank instead means the tank instantly hits itself. + Because the tank has a float position, but hit boxes are based on pixels, this problem has been deemed complex + enough to do later. These values mostly work. */ + var distance = (tank.Orientation % 4) switch + { + 0 => 4.4d, + 1 or 3 => 5.4d, + 2 => 6d, + _ => throw new UnreachableException("this should not be possible") + }; + var position = new FloatPosition( - tank.Position.X + Math.Sin(angle) * 6, - tank.Position.Y - Math.Cos(angle) * 6 + tank.Position.X + Math.Sin(angle) * distance, + tank.Position.Y - Math.Cos(angle) * distance ); - bulletManager.Spawn(new Bullet(tank.Owner, position, rotation)); + bulletManager.Spawn(tank.Owner, position, rotation); } } diff --git a/TanksServer/Models/PositionHelpers.cs b/TanksServer/Models/PositionHelpers.cs index c5ef45d..86e1790 100644 --- a/TanksServer/Models/PositionHelpers.cs +++ b/TanksServer/Models/PositionHelpers.cs @@ -8,7 +8,7 @@ internal static class PositionHelpers => new(position.X + subX, position.Y + subY); public static PixelPosition ToPixelPosition(this FloatPosition position) - => new((int)position.X, (int)position.Y); + => new((int)Math.Round(position.X), (int)Math.Round(position.Y)); public static PixelPosition ToPixelPosition(this TilePosition position) => new( (ushort)(position.X * MapService.TileSize),