Animals are placing correctly (not on house or other animal)

This commit is contained in:
d-hain 2022-06-23 23:16:30 +02:00
parent 1fd629e208
commit c40aec0022
2 changed files with 28 additions and 12 deletions

View file

@ -35,7 +35,7 @@ namespace Shop {
// Debug.Log("Buying Animal: " + Element.displayName); // Debug.Log("Buying Animal: " + Element.displayName);
} }
PlaceCowRandomlyOnScreen(); PlaceAnimalRandomlyOnScreen();
_animalShop.RemoveElement(Element, 1); _animalShop.RemoveElement(Element, 1);
} else { } else {
// Debug.Log("Not enough money to buy Animal."); // Debug.Log("Not enough money to buy Animal.");
@ -46,9 +46,13 @@ namespace Shop {
} }
/** /**
* Places cow randomly on Screen * Places cow randomly on Screen where no other invalid object is
*/ */
private void PlaceCowRandomlyOnScreen() { private void PlaceAnimalRandomlyOnScreen() {
bool objectIsAtSpawnPos;
Vector2 spawnPosition = new Vector2();
do {
objectIsAtSpawnPos = false;
float spawnY = Random.Range float spawnY = Random.Range
(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y,
Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y); Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y);
@ -56,7 +60,19 @@ namespace Shop {
(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, (Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x,
Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x); Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x);
Vector2 spawnPosition = new Vector2(spawnX, spawnY); 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<Animal>()
|| hit.collider.name == "Fence") {
objectIsAtSpawnPos = true;
}
}
} while(objectIsAtSpawnPos);
Instantiate(Element.animalPrefab, spawnPosition, Quaternion.identity); Instantiate(Element.animalPrefab, spawnPosition, Quaternion.identity);
} }
} }

View file

@ -1,2 +1,2 @@
m_EditorVersion: 2021.3.1f1 m_EditorVersion: 2021.3.2f1
m_EditorVersionWithRevision: 2021.3.1f1 (3b70a0754835) m_EditorVersionWithRevision: 2021.3.2f1 (d6360bedb9a0)