From 1bd0814e8c6e3c10c48b4f4f29859a244953282a Mon Sep 17 00:00:00 2001 From: Hans Kokx Date: Sat, 14 Mar 2026 01:06:31 +0100 Subject: [PATCH] Eliminate movement side-effect Signed-off-by: Hans Kokx --- lib/features/renderer/renderer.dart | 42 +++++++++++++++++++---------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/lib/features/renderer/renderer.dart b/lib/features/renderer/renderer.dart index 358eb12..d62a42e 100644 --- a/lib/features/renderer/renderer.dart +++ b/lib/features/renderer/renderer.dart @@ -190,7 +190,14 @@ class _WolfRendererState extends State if (player.angle < 0) player.angle += 2 * math.pi; if (player.angle >= 2 * math.pi) player.angle -= 2 * math.pi; - _applyMovementAndCollision(inputResult.movement); + Coordinate2D validatedPos = _calculateValidatedPosition( + player.position, + inputResult.movement, + ); + + player.x = validatedPos.x; + player.y = validatedPos.y; + _updateEntities(elapsed); // Explicit reassignment from a pure(r) function @@ -258,33 +265,40 @@ class _WolfRendererState extends State return (movement: movement, dAngle: dAngle); } - void _applyMovementAndCollision(Coordinate2D movement) { + Coordinate2D _calculateValidatedPosition( + Coordinate2D currentPos, + Coordinate2D movement, + ) { const double margin = 0.3; + double newX = currentPos.x; + double newY = currentPos.y; - // Calculate the intended new position - Coordinate2D newPos = player.position + movement; + // Calculate potential new coordinates + Coordinate2D target = currentPos + movement; - // Check X axis independently (allows for sliding along walls) + // Validate X (allows sliding along walls) if (movement.x != 0) { int checkX = (movement.x > 0) - ? (newPos.x + margin).toInt() - : (newPos.x - margin).toInt(); + ? (target.x + margin).toInt() + : (target.x - margin).toInt(); - if (_isWalkable(checkX, player.position.y.toInt())) { - player.x = newPos.x; + if (_isWalkable(checkX, currentPos.y.toInt())) { + newX = target.x; } } - // Check Y axis independently + // Validate Y if (movement.y != 0) { int checkY = (movement.y > 0) - ? (newPos.y + margin).toInt() - : (newPos.y - margin).toInt(); + ? (target.y + margin).toInt() + : (target.y - margin).toInt(); - if (_isWalkable(player.position.x.toInt(), checkY)) { - player.y = newPos.y; + if (_isWalkable(newX.toInt(), checkY)) { + newY = target.y; } } + + return Coordinate2D(newX, newY); } void _updateEntities(Duration elapsed) {