From 1201df46b15cce45fc851dea983de48084862ae0 Mon Sep 17 00:00:00 2001
From: Adrian Paschkowski <git@wasdennnoch.me>
Date: Thu, 15 Apr 2021 12:51:37 +0200
Subject: [PATCH] Spawn enemy at mouse position, not above

---
 Assets/Scripts/Store/EnemySpawnController.cs | 26 +++++++++++---------
 1 file changed, 15 insertions(+), 11 deletions(-)

diff --git a/Assets/Scripts/Store/EnemySpawnController.cs b/Assets/Scripts/Store/EnemySpawnController.cs
index 388b868..1539dc2 100644
--- a/Assets/Scripts/Store/EnemySpawnController.cs
+++ b/Assets/Scripts/Store/EnemySpawnController.cs
@@ -70,24 +70,16 @@ public class EnemySpawnController : MonoBehaviour
         if (StatsManager.instance.ModifyMana(-1 * (int)activeSpawn.enemyCost))
         {
             dragObject.GetComponent<Image>().sprite = activeSpawn.EnemySprite;
-            enemyImage = Instantiate(dragObject, PositionPrefab(), Quaternion.identity, transform);
+            enemyImage = Instantiate(dragObject, GetPreviewWorldPosition(), Quaternion.identity, transform);
         }
     }
 
-    Vector3 PositionPrefab()
-    {
-        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
-        pos.z = 0;
-        return pos;
-    }
-
     public void OnEnemyDrag()
     {
         if (enemyImage != null)
         {
-            enemyImage.transform.position = PositionPrefab();
+            enemyImage.transform.position = GetPreviewWorldPosition();
         }
-
     }
 
     public void OnEnemyDrop()
@@ -96,7 +88,19 @@ public class EnemySpawnController : MonoBehaviour
         {
             Destroy(enemyImage);
             enemyImage = null;
-            Instantiate(activeSpawn.enemyPrefab, PositionPrefab(), Quaternion.identity);
+            var targetPos = GetPreviewWorldPosition();
+            var newEnemy = Instantiate(activeSpawn.enemyPrefab, targetPos, Quaternion.identity);
+            // The spawned Enemy has the pivot at the bottom, not in the middle.
+            // Move it down by half its height to match the preview position.
+            targetPos.y -= newEnemy.GetComponent<SpriteRenderer>().bounds.extents.y;
+            newEnemy.transform.position = targetPos;
         }
     }
+
+    Vector3 GetPreviewWorldPosition()
+    {
+        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
+        pos.z = 0;
+        return pos;
+    }
 }
-- 
GitLab