Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by lnix_ffm · Oct 05, 2021 at 09:26 AM · positionspawning problems

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();
         }
     }
 }
 
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image OlleStarclassic · Oct 05, 2021 at 10:48 AM 0
Share

Hello :)

It sounds like you want to see if there is an object at your new spawning point before you want to spawn a new object to that point?

In that case maybe create a list of all objects already spawned so you can see what positions they have and also see if your new spawning point will be inside the bounding box of those objects already present.

You can also do boxcastall: link text

To see if your new spawning point and surrounding bounding box will come in contact with any other colliders in the scene.

When you know what colliders and attatched gameobjects to those colliders that hit your new spawning point you just take the gameobjects tag and compare it to whatever tag you want to know hit your new spawning point.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by lnix_ffm · Oct 05, 2021 at 02:00 PM

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(???)
     }
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image OlleStarclassic · Oct 05, 2021 at 04:21 PM 0
Share

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

Maybe try physics2d.overlapcircle

Good luck :) (I can see if I can write some code at the computer later but can not right now)

avatar image OlleStarclassic · Oct 05, 2021 at 06:47 PM 0
Share

Hello again :)

This might be your answer: spawn randomly positioned objects

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.

avatar image
0

Answer by OlleStarclassic · Oct 05, 2021 at 07:53 PM

Hello :)

Will try to write an answer :)

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 :)

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 :)

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();
         }
     }
 }
 


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image OlleStarclassic · Oct 05, 2021 at 08:33 PM 0
Share

Hello again :)

Just realized.

Now that we know what ranges to not use we also know what ranges to use.

So if we have two box ranges to avoid: Box 1 Min x: 0 Max x: 20 Min y: 0 Max y: 20

And Box 2: Min x : 40 Max x: 60 Min y : 40 Max y: 60

The ranges where we could create random numbers should be

For example:

  xNewSpawnPoint = Random.Range(20, 100);
     yNewSpawnPoint = random.range(0, 40);

Also for example:

 XNewSpawnPoint = Random.Range(0,40);
 YNewSpawnPoint = Random.Range(20, 100);

But I don’t know how to calculate those numbers yet. (They are very visible if you draw the bounding boxes on a piece of paper).

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

155 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Camera rotation around player while following. 6 Answers

Freeze rigidbody position without affecting rotation - please help! 1 Answer

making position checker - is area empty or not (with trigger)? 2 Answers

How to change animation in the code? 1 Answer

players positions when race ends. 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges