Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by jamb84 · Jan 07, 2017 at 08:17 PM · collisionspritesdetectionpositioninglocation

How to random place sprites but make sure they aren't touching?

Hi,

I've been trying for 2 days now to complete this task. I'll explain as much as I can. Effectively this is kind of a kid's puzzle game where they have to drag a character image from the bottom of the screen into a character shaped hole in the background. So, I have a group of sprites that I'm applying a diffuse shader to for the silhouettes. However, I don't want the toddler to be able to just memorize the pattern of where the pieces go so I'm randomizing the placement of the silhouettes on the screen. For the most part this is working ok, except for those times when the random positions overlap. I had attempted to use BoxCollider2D to determine if they were overlapping, but since all the sprites are generated at the same time and the physics doesn't have a chance to update in between, this doesn't work. At present I'm using the attached code to generate the potential Rect for each sprite and check for collissions, but for some reason it sometimes detects the collission, but other times doesn't. This is doing my head in. This is the full class code. Thanks guys.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class PuzzleScene : MonoBehaviour {
 
     Level level;
     Transform itemPanel;
     Transform gameArea;
     Rect gameBounds;
     public float worldScreenHeight;
     public float worldScreenWidth;
     List<GameObject> silhouettes = new List<GameObject>();
 
     void Start () {
         level = LevelManager.getLevelByName (GameManager.level);
         itemPanel = GameObject.Find ("ItemPanelContent").transform;
         gameArea = GameObject.Find ("Background").transform;
         getWorldSize ();
         setBackground ();
         populateItems ();
     }
 
     void getWorldSize() {
         worldScreenHeight = Camera.main.orthographicSize *2f;
         worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
     }
 
     void setBackground() {
         SpriteRenderer sr = gameArea.gameObject.GetComponent<SpriteRenderer> ();
         sr.sprite = Resources.Load<Sprite>(level.Background);
         float scaleX = worldScreenWidth / sr.sprite.bounds.size.x;
         float scaleY = worldScreenHeight / sr.sprite.bounds.size.y;
         gameArea.localScale = new Vector3(scaleX, scaleY, 1);
         gameBounds = getSpriteRect (gameArea.gameObject);
     }
 
     void populateItems() {
         for (int i = 0; i < level.Items.Count; i++) {
             GameObject item = createItem (level.Items [i]);
             item.transform.SetParent (itemPanel);
 
             GameObject sil = createSilhouette (level.Items [i]);
             sil.transform.SetParent (gameArea);
             silhouettes.Add (sil);
         }
     }
 
     GameObject createItem(LevelItem item) {
         GameObject obj = Instantiate(Resources.Load ("PuzzlePiece") as GameObject, transform);
         Image spr = obj.GetComponent<Image>();
         obj.name = item.Name;
         spr.sprite = Resources.Load<Sprite> (item.Sprite);
         return obj;
     }
 
     GameObject createSilhouette(LevelItem item) {
         GameObject obj = Instantiate(Resources.Load ("Silhouette") as GameObject, transform);
         SpriteRenderer spr = obj.GetComponent<SpriteRenderer>();
         spr.sprite = Resources.Load<Sprite> (item.Sprite);
         obj.name = item.Name;
         float ppu = spr.sprite.pixelsPerUnit;
         float unitSize = 100 / ppu;
         float scaleX = unitSize / spr.sprite.bounds.size.x;
         float scaleY = unitSize / spr.sprite.bounds.size.y;
         obj.transform.localScale = new Vector3 (scaleX, scaleY, 1);
         do {
             randomPosition(obj);
         } while (isColliding(obj));
         return obj;
     }
 
     bool isColliding(GameObject obj) {
         Rect testRect = getSpriteRect (obj);
         foreach (GameObject obje in silhouettes) {
             Rect r = getSpriteRect (obje);
             if (r.Overlaps(testRect)) {
                 return true;
             }
         };
         return false;
     }
 
     void randomPosition(GameObject obj) {
         obj.transform.position = new Vector3 (Random.Range (-5f, 5f), Random.Range (-2f, 2f), 0);
     }
 
     Rect getSpriteRect(GameObject obj) {
         Vector3 pos = obj.transform.position;
         SpriteRenderer sr = obj.GetComponent<SpriteRenderer> ();
         Rect tmpr = new Rect ();
         Vector3 min = pos + sr.bounds.min;
         Vector3 max = pos + sr.bounds.max;
         min.Scale (obj.transform.localScale);
         max.Scale (obj.transform.localScale);
         tmpr.min = new Vector2 (min.x, min.y);
         tmpr.max = new Vector2 (max.x, max.y);
         return tmpr;
     }
 
 }
 
 


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

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by jamb84 · Jan 13, 2017 at 12:43 AM

Figured it out. I wasn't taking into account the center of the rect.

 Rect getSpriteRect(GameObject obj) {
         Vector3 pos = obj.transform.position;
         SpriteRenderer sr = obj.GetComponent<SpriteRenderer> ();
         Rect tmpr = new Rect (obj.transform.position, sr.bounds.size);
         tmpr.center = tmpr.min;
         return tmpr;
     }

Comment
Add comment · 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

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

118 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

Related Questions

Selective Collision Detection 2 Answers

My collision is not detecting 1 Answer

Best way to do Collision detection when you have multiple enemies/allies around you 0 Answers

Checking for collisions 1 Answer

Detect edge collision...? 0 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