• 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 Goodgamejuli · Feb 09, 2020 at 10:59 AM · collisionobjectcodepagedistance checknearest

How could I calculate the distance to recieve the nearest object to the player?

The problem is that i cant set the rockets (player) position to the closest Planet when it should landing like in this little flashgame: https://armorgames.com/play/12015/run-from-the-sun How could I calculate the nearest Planet in help of Distance/Collission?

Here is something that I´v tried but it isnt working:

 void Update()
     {
       
         Distance = Vector3.Distance(GameObject.Find("Rakete").transform.position, GameObject.Find("Planet(Clone)").transform.position);
         if (Aktivierunsvariable == true)
         {
             if (Distance < 10)
             {
                 GameObject.Find("Rakete").transform.parent = GameObject.Find("Planet(Clone)").transform;//setchild
                 Flugerlaubt = false;
                 Aktivierunsvariable = false;
             }
 
             if (Distance > 10)
             {                
                 Aktivierunsvariable = true;
             }
         }
 
 
         //KEYBOARD SPACE (setzt Flugerlaubnis auf true)
         if (Input.GetKeyDown("space"))
         {
             GameObject.Find("Rakete").transform.parent = null;//unchild
             Flugerlaubt = true;
             
         }
         //Flugvariable (Rakete fliegt los) 
         if (Flugerlaubt == true)
         {
             //Rakete fliegt vorwärts
             GameObject.Find("Rakete").transform.Translate(Vector3.up * 1 * Time.deltaTime);
         }
 
     }






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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by martygrof3708 · Feb 09, 2020 at 11:13 AM

 using System.Collections.Generic;
 using UnityEngine;
 
 public class FindNearestPlanet : MonoBehaviour
 {
     // You need to store a list of all of the planets
     // If you add them procedurally, you need to update this list each time to add or remove a planet
     private List<Transform> planetTransforms; 
     private Transform targetPlanetTransform; // The current planet we are moving to if we find one
     private Transform playerTransform;
     private float minDistance = 10f;
     private float flyingSpeed = 5f;
 
     // State of player
     private bool onPlanet = false;
     private bool flying = false;
     private bool foundPlanet = false;
 
     private void Update()
     {
         if ( onPlanet )
         {
             // You would put the code to rotate the player with the planet in here, ok?
             // If you are setting the planet as parent of ship, the ship SHOULD rotate with the planet,
             // If the planet is rotating
 
             if ( Input.GetKeyDown( KeyCode.Space ) )
             {
                 // Change state of player
                 onPlanet = false;
                 flying = true;
 
                 // Detach from the planet
                 playerTransform.parent = null;
             }
         }
         else if ( flying )
         {
             if ( !foundPlanet )
             {
                 // If the player is flying but not found a planet, move the ship
                 // Again, you would have to calculate the x and y speeds based on the angle of your ship when it left the planet
                 // So this line is just example
                 playerTransform.Translate( new Vector3( flyingSpeed , flyingSpeed , 0 ) );
 
                 // Then we check for the nearest planet
                 int closestIndex = 0; // Keep track of index in the list of planetTransforms
                 float shortestDistance = 100; // Used to compare each distance, I put it at 100 to start for simplicity
                 float currentDistance = 0;
 
                 // Loop through the list
                 for ( int i = 0; i < planetTransforms.Count; i++ )
                 {
                     currentDistance = Vector3.Distance( playerTransform.position , planetTransforms[ i ].position );
 
                     if ( currentDistance < minDistance && currentDistance < shortestDistance )
                     {
                         // if the distance to the current planet in the list is closer than the previous shortestDistance, store the list info
                         closestIndex = i;
                         shortestDistance = currentDistance;
 
                         // So once we find it we arent checking distance every frame
                         foundPlanet = true;
                     }
                 }
 
                 // Once we are done looping, we have the index of the transform with the clostest distance, so we set that
                 // So our ship can move to that location (targetPlanetTransform)
                 targetPlanetTransform = planetTransforms[ closestIndex ];
             }
             else // Otherwise if we found a planet, move the player towards it
             {
                 playerTransform.position = Vector3.Lerp( playerTransform.position , targetPlanetTransform.position , 0.125f );
 
                 float distanceToPlanet = Vector3.Distance( playerTransform.position , targetPlanetTransform.position );
 
                 // Or whetever distance u like,
                 // You may have to do a little calculation if you want the ship to go right on the edge of the planet
                 if ( distanceToPlanet < 0.1f )
                 {
                     Vector3 direction = Vector3.Normalize( playerTransform.position - targetPlanetTransform.position );
                     float radius = targetPlanetTransform.localScale.x / 2;
                     Vector3 edgeOfCircle = targetPlanetTransform.position + ( direction * radius );
 
                     playerTransform.position = edgeOfCircle;
                     playerTransform.SetParent( targetPlanetTransform );
 
                     // Set state
                     flying = false;
                     onPlanet = true;
                 }
             }
         }
     }
 }
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 Goodgamejuli · Feb 09, 2020 at 10:57 PM 0
Share

Thanks for the advice, but i want a script which can pick the nearest planet to the rocket like in the game to land on, maybe by on collission or with the help of distance. Then i will child the rocket to the nearest planet. When I press a button, the rocket should start again so i would unchild it. Im a bloody beginner... pls help :)

avatar image martygrof3708 Goodgamejuli · Feb 10, 2020 at 12:12 AM 0
Share

I've updated my answer.

avatar image
0

Answer by Goodgamejuli · Feb 10, 2020 at 04:13 PM

Thank you very very much, but i'm too inexperienced to adjust the script (to my scene). I'm really new at Unity. I´ve uploudet the project in a zip file: http://www.mediafire.com/file/d5kp6bsy636g3oo/SUNRUN.zip/file.

best regards

Comment
Add comment · Show 3 · 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 martygrof3708 · Feb 10, 2020 at 05:37 PM 0
Share

Its actually quite easy.

 public class PlanerSpawner : $$anonymous$$onoBehaviour
 {
     // A reference to the planetScript
     private FindNearestPlanet script;
     // You can just drag a prefab here in the editor
     public GameObject planetPrefab;
 
     private void Start()
     {
         script = GameObject.Find( "FindNearestPlanetObject" ).GetComponent<FindNearestPlanet>();
 
         for ( int i = 0; i < 10; i++ )
         {
             script.planetTransforms.Add( Instantiate( planetPrefab ).transform );
         }
     }
 
     private void Update()
     {
         // When you want to add a planet
         script.planetTransforms.Add( Instantiate( planetPrefab ).transform );
 
         // When you want to remove a planet
         script.planetTransforms.RemoveAt( 0 );
         // This will remove the first planet in the list
     }
 }

This is really the simplest way to do it.

avatar image ShadyProductions · Feb 10, 2020 at 05:58 PM 1
Share

Perhaps you should try to learn some basic C# before you attempt more complicated unity projects. Start small.

avatar image Goodgamejuli · Feb 11, 2020 at 04:49 PM 0
Share

Thanks for the effort, I only started Unity a few days ago. I previously worked with Construct 2. I have a lot to learn. I have adjusted the script so that the rocket lands correctly on the planet. Unfortunately I couldn't manage the rest. $$anonymous$$aybe someone can be found to complete the little project which I uploaded: http://www.mediafire.com/file/06j5uuqs1d9uxg6/SUNRUN.zip/file. It is smaller than 25 mb and could be sent by email. :)

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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

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

How can I change camera when colliding with "X" object? 1 Answer

Making an object a child on collision 1 Answer

How to see object through collision? 0 Answers

Fast moving object passing through other objects. 7 Answers

[SOLVED] Keep a specific object from killing the player? 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges