- Home /
How to have pickups not spawn on top of the player?
I know what my problem is. The nonSpawnArea is a point and not an area/square and the if statement shouldn't check weather the flyPosition is the nonSpawnArea, but it should check weather it is within the area. So how would I change these two things.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlySpawner : MonoBehaviour {
[SerializeField]
private GameObject flyPrefab;
[SerializeField]
private GameObject player;
[SerializeField]
private int totalFlyMinimun = 12;
[SerializeField]
private float spawnArea = 25f;
private Vector3 nonSpawnArea;
public static int totalFlies;
// Use this for initialization
void Start () {
totalFlies = 0;
}
// Update is called once per frame
void Update () {
// While the total number of flies is less than the minimum...
while (totalFlies < totalFlyMinimun) {
// ...then increment the total number of flies
totalFlies++;
// ...create the area in which the flies can not spawn in
nonSpawnArea = new Vector3 (player.transform.position.x + 3f, 2f, player.transform.position.z + 3f);
// ...create a random position for a fly...
float positionX = Random.Range(-spawnArea, spawnArea);
float positionZ = Random.Range(-spawnArea, spawnArea);
Vector3 flyPosition = new Vector3 (positionX, 2f, positionZ);
// ...check that the fly isn't spawning on top of the player
if (flyPosition != nonSpawnArea) {
// ...and create a new fly
Instantiate(flyPrefab, flyPosition, Quaternion.identity);
}
}
}
}
Also if you have a better way of doing this please inform me.
Answer by Glurth · Nov 24, 2017 at 06:19 PM
Assuming your player has a MeshRender component you can use the BOUNDS member, to determine the extents of the player object, in worldspace.
https://docs.unity3d.com/ScriptReference/Renderer-bounds.html
Then when setting the position of the new object, you can simply offset it, from the players position (or the Bound's center), by the extents of the Bounds. I would probabaly only adjust the x and/or y values of the final position, so it remains at the same z (height) of the player.
https://docs.unity3d.com/ScriptReference/Bounds-extents.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612143236im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Timer Rewind Script not counting time correctly 0 Answers
How can i use a button key click to switch/toggle between enum options ? 1 Answer
WebGL audio and Slider Interaction 0 Answers