From c40aec0022dad3151495fb2bf65491fae04bda20 Mon Sep 17 00:00:00 2001 From: d-hain Date: Thu, 23 Jun 2022 23:16:30 +0200 Subject: [PATCH] Animals are placing correctly (not on house or other animal) --- Assets/Scripts/Shop/AnimalShopSlot.cs | 36 +++++++++++++++++++-------- ProjectSettings/ProjectVersion.txt | 4 +-- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/Assets/Scripts/Shop/AnimalShopSlot.cs b/Assets/Scripts/Shop/AnimalShopSlot.cs index 37ba048..411f4ea 100644 --- a/Assets/Scripts/Shop/AnimalShopSlot.cs +++ b/Assets/Scripts/Shop/AnimalShopSlot.cs @@ -35,7 +35,7 @@ namespace Shop { // Debug.Log("Buying Animal: " + Element.displayName); } - PlaceCowRandomlyOnScreen(); + PlaceAnimalRandomlyOnScreen(); _animalShop.RemoveElement(Element, 1); } else { // Debug.Log("Not enough money to buy Animal."); @@ -46,17 +46,33 @@ namespace Shop { } /** - * Places cow randomly on Screen + * Places cow randomly on Screen where no other invalid object is */ - private void PlaceCowRandomlyOnScreen() { - float spawnY = Random.Range - (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, - Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y); - float spawnX = Random.Range - (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, - Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x); + private void PlaceAnimalRandomlyOnScreen() { + bool objectIsAtSpawnPos; + Vector2 spawnPosition = new Vector2(); + do { + objectIsAtSpawnPos = false; + float spawnY = Random.Range + (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, + Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y); + float spawnX = Random.Range + (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, + Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x); + + spawnPosition = new Vector2(spawnX, spawnY); + + // check if any Object is already at that position + RaycastHit2D hit = Physics2D.Raycast(spawnPosition, Vector2.up, 0f); + if(hit.collider != null) { + if(hit.collider.name == "House" + || hit.collider.GetComponent() + || hit.collider.name == "Fence") { + objectIsAtSpawnPos = true; + } + } + } while(objectIsAtSpawnPos); - Vector2 spawnPosition = new Vector2(spawnX, spawnY); Instantiate(Element.animalPrefab, spawnPosition, Quaternion.identity); } } diff --git a/ProjectSettings/ProjectVersion.txt b/ProjectSettings/ProjectVersion.txt index 90d6509..3dcb827 100644 --- a/ProjectSettings/ProjectVersion.txt +++ b/ProjectSettings/ProjectVersion.txt @@ -1,2 +1,2 @@ -m_EditorVersion: 2021.3.1f1 -m_EditorVersionWithRevision: 2021.3.1f1 (3b70a0754835) +m_EditorVersion: 2021.3.2f1 +m_EditorVersionWithRevision: 2021.3.2f1 (d6360bedb9a0)