• 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 MikHolmes · Jul 21, 2020 at 04:46 AM · collision detectioninstantiate prefab

Level Generation collision checking erratic

I'm trying to adapt a level generation tutorial and I've stumbled on checking collisions between rooms. I've spent a few days searching but can't find answers that particularly help, so I think there might be a few overlapping issues. Right now, most of the time it works fine, but every so often it places a room directly inside another room, and I'm baffled. I know it's not a great idea to just copy tutorials without fully understanding it, but I'm not sure what to even start learning about.

The idea is to place a start room, pick a doorway of the room, create a new room and position/rotate it so doorways match, then continue adding rooms until the limit is reached. If a room has no legal position, it'll restart.

This is taking place in a coroutine - something I don't fully understand, but I believe we're using it because physics requires a frame (right?). In GenerateLevel(), the PlaceRoom() that's called attempts to instantiate a room prefab, selects room nodes, runs PositionRoomAtExit(), then runs CheckRoomOverlap(room). If it fails, it destroys the game object, sets resetLevelGen to true, which should call ResetLevelGen() in the coroutine.

I'm not certain why it works most of the time, but once in a while just fails like this. Any help would be greatly appreciated!

 private void Start()
  {
      levelGenCoroutine = StartCoroutine(GenerateLevel());
  }
  
  IEnumerator GenerateLevel()
  {
      //Declare some time intervals to wait for things to update before actually checking physics.
      WaitForSeconds startup = new WaitForSeconds(1);
      WaitForFixedUpdate interval = new WaitForFixedUpdate();
      //Wait a sec to let Physics exist.
      yield return startup;
      //Place Start Room
      PlaceStartRoom();
      yield return interval;
      //Figure out how many rooms we're placing.
      int roomsToPlace = Random.Range((int)numRoomsToPlace.x, (int)numRoomsToPlace.y);
  
      //Place rooms one by one.
      for (int i = 0; i < roomsToPlace; i++)
      {
          PlaceRoom();
          yield return interval;
          if (resetLevelGen) {
              ResetLevelGen();
              break;
          } 
      }
      /////In theory we can place the end room here.
      Debug.Log("Level Generator Finished");
      WaitForSeconds wait = new WaitForSeconds(5);
      yield return wait;
      ResetLevelGen();
  }
  
  void PositionRoomAtExit(ref Room room, Exit newExit, Exit targetExit)
  {
      //Position this room at the origin.
      room.transform.position = Vector3.zero;
      room.transform.rotation = Quaternion.identity;
      //Rotate the room to meet the rotation of the target.
      Vector3 targetEuler = targetExit.transform.eulerAngles;
      Vector3 newEuler = newExit.transform.eulerAngles;
      float deltaAngle = Mathf.DeltaAngle(newEuler.y, targetEuler.y);
      Quaternion oldRotation = Quaternion.AngleAxis(deltaAngle, Vector3.up);
      room.transform.rotation = oldRotation * Quaternion.Euler(0, 180f, 0);
      //Position room to meet the doorway
      Vector3 positionOffset = newExit.transform.position - room.transform.position;
      //I'm not sure if this'll fix anything, but I'm rounding the position to be sure.
      room.transform.position = targetExit.transform.position - positionOffset;
      Vector3 snap = new Vector3( 
          Mathf.Round(room.transform.position.x),
          Mathf.Round(room.transform.position.y),
          Mathf.Round(room.transform.position.z));
      room.transform.position = snap;
  }
  
  bool CheckRoomOverlap(Room newRoom)
  {
      Bounds newBounds = newRoom.RoomBounds;
      newBounds.center = newRoom.transform.position;
      newBounds.Expand(-0.1f);
  
      Collider[] colliders = Physics.OverlapBox(newBounds.center, newBounds.extents, newRoom.transform.rotation);
  
      if (colliders.Length > 0)
      {
          //Ignore collisions with current room
          foreach(Collider c in colliders)
          {
              if (c.transform.parent.gameObject.Equals(newRoom.gameObject))
              //if (c.transform.gameObject.Equals(newRoom.gameObject))
              {
                  continue;
              } else
              {
                  //Debug.LogError("Collision Found at: " + newBounds.center + " and " + c.transform.position);
                  Debug.Log(newRoom.name + " at " + newBounds.center + "(andshouldbe) " + newRoom.transform.position + " colliding with " + c.transform.parent.gameObject.name);
                  return true;
              }
          }
      }
      return false;
  }
  
  void ResetLevelGen()
  {
      Debug.Log("RESTARTING LEVEL GENERATOR");
      foreach (Room room in placedRooms)
      {
          Destroy(room.gameObject);
      }
      placedRooms.Clear();
      resetLevelGen = false;
      StopCoroutine(levelGenCoroutine);
      levelGenCoroutine = StartCoroutine(GenerateLevel());
  }
Comment
Add comment
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

0 Replies

· Add your reply
  • Sort: 

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

133 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

Related Questions

Instantiated object that has a collision is not firing OnCollisionEnter2D 1 Answer

Collision not detecting between two instantiated objects 1 Answer

Stopping bullets from outside forcefield 2 Answers

How to detect when two gameObjects collide by name {java, 2d} 2 Answers

Why is OnTriggerStay is not working? 1 Answer


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