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 itsmealex100 · May 11, 2015 at 06:02 PM · c#spawn

Instantiate away from player but within screen

Hi there, In my 2D game, game objects regularly spawn around the player, they can spawn anywhere on the screen as long as they stay within the screen as the player does not move. However the problem I have is that sometimes objects spawn directly under the player and cannot be seen.

How can I make sure the objects spawn a certain distance away from the player but still within the screen.

This is what I am using at the moment, any help would be great?

 GameObject point = GameObject.Instantiate (objectToSpawn, new Vector2 (Random.Range (-3, 3), Random.Range (-4, 6)), Quaternion.identity) as GameObject;

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

4 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by FortisVenaliter · May 12, 2015 at 09:46 AM

Generate the random location first, not in the method call. Then you can do something like

 if((newPos-playerPos).magnitude < minDistance)
     newPos = [regenerate here];

Then just pass the newPos to the instantiate function once you know you have a good one.

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
avatar image
0

Answer by xortrox · May 12, 2015 at 10:24 AM

Untested. Note that Random.Range(int,int) returns a value that doesn't include the second value because integers are used. If you want a much "smoother" range change them for floats.

 int endlessLoopCount = 0;
 bool error = false;
 Vector2 point = GetRandomPoint();
 
 /*
 this will keep getting a new point if the generated point is within minimumDistanceFromPlayer
 it also prevents locking up the game incase the point is within minimumDistanceFromPlayer 30 times in a row, or if something goes wrong it wont lock up unity and require a restart.
 */
 
 while(Vector2.Distance(point, playerPosition) < minimumDistanceFromPlayer || endlessLoopCount > 30)
 {
 
 point = GetRandomPoint();
 endlessLoopCount++;
 if(endlessLoopCount > 30)
 {
 Debug.Log("Something made GetRandomPoint() return within minimumDistance too many times, exiting.");
 error = true;
 }
 
 }
 if(!error)
 {
 GameObject = (GameObject)Instantiate(objectToSpawn, point, Quaternion.identity);
 }

 //this will get a point from (-3 to 2, -4 to 5)
 Vector2 GetRandomPoint()
 {
 
 return new Vector2(Random.[Range][1](-3,3), Random.Range(-4,6));
 
 }

[1]: http://docs.unity3d.com/ScriptReference/Random.Range.html

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
avatar image
0

Answer by itsmealex100 · May 12, 2015 at 12:31 PM

Hi, thanks for both suggestions! Although fortunately I managed to get this working last night using the code below. It just does a simple check distance and then restarts the function and breaks if it needs to. However as Xortrox pointed out, there is always the Small chance that the function could loop forever, can you spot any easy way to counter this as you have done in yours?

 void GreenLightsOn () {
  
         for (var i = 0; i < Random.Range(1,GreensSpawnAmount); i++) {
             GameObject spawnedLight = GameObject.Instantiate (light, new Vector2 (Random.Range (-3, 3), Random.Range (-4, 6)), Quaternion.identity) as GameObject;
             float dist = Vector2.Distance (spawnedLight.transform.position,transform.position);
 
 
         if(dist <= 0.7f) {
                 Destroy (spawnedLight);
                 GreenLightsOn();
                 Debug.Log ("TOO CLOSE");
                 break;
             }
             clickScreen.GetComponent<ClickScreen> ().Spawned ++;
         }
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 itsmealex100 · May 12, 2015 at 01:03 PM 0
Share

Also, another problem I'm having is that on very rare occasions, the spawnLight's can spawn on top of each other, Any ideas on how I can solve this?

avatar image FortisVenaliter · May 12, 2015 at 04:43 PM 0
Share

You would have to loop through the existing ones and check the distance to them as well.

It shouldn't loop forever unless the space is too small or too filled up, but then you can just add a counter variable and break it if it hits like 100 or something.

avatar image
0

Answer by barbe63 · May 13, 2015 at 02:03 AM

As long as you know the max radius you want I think this might be your friend: http://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html

Then if you want a minimum distance I would do something like this:

 while(Vector2.distance(player.transform.position, instantiatedStuff.transform.position) < minDistance)
 {
    instantiatedStuff.transform.position += (instatiatedStuff.transform.position - player.transform.position).normalized;
 }
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

21 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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Need help with my shop system (spawning same weapon no matter what) 1 Answer

Enemies spawning on top of each other fix? 1 Answer

Increasing spawn rate over time 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