check if there is an object at position 2d with a tag,How to check if there an object at position with tag. 2d

Hi,

I would like to check a position for spawning. Checking if there an exists object with a special tag like “Obstacle” at the new spawning point.

I tried it with OnTriggerEnter2D but it don’t work correctly. Sometimes it’s work.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Food : MonoBehaviour
{
    public BoxCollider2D gridArea;

    private void RandomizePosition()
    {
        Bounds bounds = this.gridArea.bounds;

        float x = Random.Range(bounds.min.x, bounds.max.x);
        float y = Random.Range(bounds.min.y, bounds.max.y);

        Vector3 spawnPos = new Vector3(Mathf.Round(x), Mathf.Round(y), 0.0f);

        this.transform.position = spawnPos;

    }

    // Start is called before the first frame update
    void Start()
    {
        RandomizePosition();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log(other);
        if (other.tag == "Player")
        {
            RandomizePosition();
        }
        if (other.tag == "Obstacle")
        {
            RandomizePosition();
        }
    }
}

2 Answers

2

thank you. Yes I would like to want to see if there an object before to spawn. How it works with the boxcastall? I don’t understand the syntax.

    private void CheckObstacle()
    {
        RaycastHit2D boxResult;
        boxResult = Physics2D.BoxCastAll(???)
    }

Hello :) Google: > Object detect collision with other object > before spawning Lot’s of people have this problem. Lot’s of answers. Here’s one: [check before spawning][1] Maybe try [physics2d.overlapcircle][2] [1]: https://answers.unity.com/questions/41115/check-for-collision-before-instantiating.html [2]: https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html Good luck :) (I can see if I can write some code at the computer later but can not right now)

Hello again :) This might be your answer: [spawn randomly positioned objects][1] [1]: https://answers.unity.com/questions/1721359/how-to-spawn-randomly-positioned-objects-without-o.html But a problem is when you do randomly created spawn points in a loop and test and see if you hit a collider it might take forever until you hit a point free from collider hits.

Hello :slight_smile:

Will try to write an answer :slight_smile:

Think you can solve it like this but have not tested it in code.

Say you have all the objects and its surrounding bounding boxes in a list.

Then you know what spawn points to avoid.

You have to take one object from the list.
Get its bounding box’s min and max values for x and y.
Take min value for x (for example 5)
Then take your new spawn objects radius (for example 5). (From its center to the bounding box).
Take min value for x (5) and remove new objects spawn radius (5).
Result 0.
That way we have minimum range for x for new spawn point to avoid.
Do the same for the max value for x.
Take the max x value for objects bounding box (for example 15).
Take the new objects spawn radius (5) and add that to the max x bounding box (15).
Result 20.
Then we have max range for x.

Do the same thing but for y values.
Min and max bounding box y (for example 5 and 15) and remove and add new objects radius.
Result min y 0 and max y 20.

Now we have min and max range for x and min and max range for y.

Now the new object can only be spawned if it is NOT within this range.

Since we can create random numbers blazingly fast we can get a spawning point outside of this range pretty fast.

So min x is 0 and max x 20.
And min y is 0 and max y is 20.

So the random numbers for new spawn point should be

xNewSpawnPoint = Random.Range(0, 100);
yNewSpawnPoint = Random.Range(0,100);
If( xNewSpawnPoint < 0 && xNewSpawnPoint > 20 &&
yNewSpawnPoint < 0 && yNewSpawnPoint > 20)
spawnPointValid == true

Loop above code until spawnPointValid is true

If you have more than one object to look out for the loop has to go through all objects to look out for and build ranges that the numbers for xNewSpawnPoint and ySpawnPoint can not be within.

I am sure Unity has a better way if doing this but this will be the solution the old fashioned way before we had game engines :slight_smile:

I am pretty sure this could be applied for objects spawned in 3d as well as long as we know the bounding boxes of the objects.

Good luck now :slight_smile:

Edit:
Here is a code example doing what I said in the answer:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spawn : MonoBehaviour
{
    public GameObject spawnObject;


    public List<GameObject> obstacles;

    // Start is called before the first frame update
    void Start()
    {
        SpawnObject();
    }

    private void SpawnObject()
    {
        GameObject background = GameObject.Find("background");
        Renderer renderer = background.GetComponent<Renderer>();

        float backgroundMinX = renderer.bounds.min.x;
        float backgroundMaxX = renderer.bounds.max.x;
        float backgroundMinY = renderer.bounds.min.y;
        float backgroundMaxY = renderer.bounds.max.y;

        bool foundObstacle = false;

        float spawnX = 0f;
        float spawnY = 0f;
        float spawnZ = 0f;

        do
        {
            foundObstacle = false;

            spawnX = UnityEngine.Random.Range(backgroundMinX, backgroundMaxX);
            spawnY = UnityEngine.Random.Range(backgroundMinY, backgroundMaxY);

            Renderer spawnObjectRenderer = spawnObject.GetComponent<Renderer>();
            Vector3 extents = spawnObjectRenderer.bounds.extents;


            foreach (GameObject obstacle in obstacles)
            {
                Renderer obstacleRenderer = obstacle.GetComponent<Renderer>();

                float obstacleMinX = obstacleRenderer.bounds.min.x;
                float obstacleMaxX = obstacleRenderer.bounds.max.x;
                float obstacleMinY = obstacleRenderer.bounds.min.y;
                float obstacleMaxY = obstacleRenderer.bounds.max.y;

                if (spawnX + extents.x  > obstacleMinX && spawnX - extents.x < obstacleMaxX &&
                    spawnY + extents.y > obstacleMinY && spawnY - extents.y < obstacleMaxY)
                {
                    foundObstacle = true;
                }
            }
        }
        while (foundObstacle == true);

        Vector3 position = new Vector3(spawnX, spawnY, spawnZ);

        Instantiate(spawnObject, position, Quaternion.identity);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            SpawnObject();
        }
    }
}