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 Trozomuro · Apr 28, 2015 at 09:57 AM · movementtransformdistancenoob

How to calculate distance between objects?

Im a little noob in the unity enviroment, but, i need that one rigidbody2d find the nearest object with a specific tag, and then, move to them. I tried tons of things, tons of diferents arrays, findobjectswithtag();, but i dont know how to manipulate the transform data to achieve this. I think that is pretty basic, but i cant handle...

Do you can write an example please?

Thanks.

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 Trozomuro · Apr 30, 2015 at 06:35 PM 0
Share

Thanks for your attention.

5 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by YoungDeveloper · Apr 28, 2015 at 10:18 AM

  • Use SphereCast to get gameobjects in certain radius, then loop through them and get whatever you want.

  • Use Vector3.Distance to get the distance.

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
1

Answer by siaran · Apr 28, 2015 at 10:07 AM

okay, simple example of finding the closest object with a tag

 GameObject FindClosestTag(string tag){
 
   //get all the gameobjects with a tag
   GameObject[] tagged = GameObject.FindGameObjectsWithTag(tag);
   //closest object found so far
   GameObject closest = null;
   //the shortest distance we've found so far
   float shortestDistance = float.PositiveInfinity;
   //loop trough all gameobjects we found with the tag
   foreach(GameObject go in tagged){
    //we don't want to have ourself be an option for the closest object
    if(go != this.gameObject){
      //the distance to the current gameobject
      float currentDistance = Vector3.Distance(transform.position, go.transform.position);
      //this object is closer than the closest one so far 
      //this one becomes the closest one so far
      if(currentDistance < shortestDistance){
       shortestDistance = currentDistance;
       closest = go;
      }
    }
   }
 
  //return the gameobject we found
  return closest;
 }

not a very optimized code snip, but should do what you need.

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 Pangamini · Apr 28, 2015 at 01:08 PM 0
Share

Don't use Vector3.Distance, it calculates an expensive Square root function. Ins$$anonymous$$d, subtract the vectors and calculate sqr$$anonymous$$agnitude, it's the distance squared. But since the square is one to one function (in positive domain), it's enough to compare squared distances.

avatar image AlucardJay · Apr 28, 2015 at 01:21 PM 1
Share

Interesting info about using Distance :

  • http://answers.unity3d.com/questions/125882/vectordistance-performance.html

  • http://answers.unity3d.com/questions/307612/inversetransformpoint-vs-vector3distance-which-is.html

  • http://answers.unity3d.com/questions/384932/best-way-to-find-distance.html

Surprised me too!

avatar image HarshadK · Apr 28, 2015 at 01:34 PM 0
Share

@alucardj

Surprised me too!

True that!

avatar image
0

Answer by Xarbrough · Apr 28, 2015 at 10:19 AM

Here is some code to get you started on how to move towards another object within a certain distance:

 using UnityEngine;
 using System.Collections;
 
 public class ObjectA : MonoBehaviour {
 
     // The distance beneath which objectA will move towards objectB in world units
     public float searchRadius = 10f;
 
     // Speed of this object when moving towards the target
     public float speed = 1f;
 
     // The target to follow
     private GameObject objectB;
 
     // Our own rigidbody
     private Rigidbody2D rb;
 
 
     void Start () {
 
         // Get the rb2D component from this object
         rb = GetComponent<Rigidbody2D>();
 
         // Find the other object by Tag, it must already exist on scene creation
         objectB = GameObject.FindGameObjectWithTag("tagofObjectB");
     }
 
     // FixedUpdate because we are moving rigidbody that need to be in sync with other Physics actions
     void FixedUpdate () {
 
         // Calculate the distance between both objects
         float distance = Vector3.Distance(objectB.transform.position, transform.position);
 
         // If the distance is smaller than the given threshold
         if(distance < searchRadius) {
 
             // Calculate the direction from our object to objectB
             Vector2 direction = objectB.transform.position - transform.position;
 
             // Move with our rigidbody towards the other object in a straight line
             // Can be stopped by other colliders or forces
             rb.MovePosition(rb.position + direction * speed * Time.fixedDeltaTime);
         }
     }
 }
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 Xeong-Hu · Apr 28, 2015 at 01:40 PM

Try this out dude. It's what I'm currently doing now to determine the distance of my AI Character and Player. So like if it's too close then he'll do this thingy and if far away he'll do something else.

     public Vector2 RelativePoint;
     public Transform YourTransform;
 
 
 
 
         if(YourTarget != null){
         RelativePoint = YourTransform.InverseTransformPoint(YourTarget.transform.position);
 
         }

Attach this code to your Character or what ever object you'd like to use then

Drag Your GameObject with the script into the YourTransform

And then next

Create a GameObject (or not) Drag that GameObject into your public Gameobject named YourTarget

Start the game and you'll see numbers ranging in your Public Vector RelativePoint.

Pretty simple man. It works for me, I hope it does the same for you as well.

: )

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 Xeong-Hu · Apr 28, 2015 at 02:01 PM 0
Share

http://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html Check this out for more info.

InverseTransformPoint is where the magic is.

avatar image
0

Answer by Trozomuro · Apr 30, 2015 at 06:38 PM

Ok, i saw my error, i actually do everything right, only i use incorrectly the "go" in: foreach (GameObject go in tagged)

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

6 People are following this question.

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

Related Questions

How to translate a camera forward and back(basically a zoom) according to the distance of two objects? 1 Answer

How to drag and drop a instantiate prefab on my mobile game 3D using touchs! 0 Answers

Raycast distance affected by momentum of character 0 Answers

Transform position of an object at particular angle/direction 3 Answers

Movement Script Help 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