Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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
17
Question by Mattivc · Mar 17, 2010 at 09:14 PM · javascript-specific

Calculate distance between two objects

How can i calculate the distance between two objects in unity using javascript?

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

6 Replies

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

Answer by Eric5h5 · Mar 17, 2010 at 09:49 PM

var distance = Vector3.Distance(object1.transform.position, object2.transform.position);
Comment
Add comment · Show 4 · 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 witchking409 · Jul 25, 2013 at 01:44 PM 5
Share

For those who want C#

public float distance; // distance between enemies and players public Transform target;

 void Update()
 {
 distance =Vector3.Distance(transform.position,target.position);
 }
avatar image Rexor4321 witchking409 · Sep 12, 2017 at 01:26 PM 0
Share

Thank you!

avatar image impurekind Rexor4321 · Aug 10, 2018 at 01:23 PM 0
Share

I clearly don't understand how this works because it isn't working properly with my game and I don't know why:

I have this script attached to my player character:

 public class IsPlayerNextToDoor : $$anonymous$$onoBehaviour
 {
     public Transform door;
     float distance;
     public float maxAllowedDistance = 3f;
 
     private void Update()
     {
         distance = Vector3.Distance(transform.position, door.position);
 
         if (distance < maxAllowedDistance)
         {
             isPlayerCloseToDoor = true;
             print("Player is close to door");
         }
         else
         {
             isPlayerCloseToDoor = false;
             print("Player is too far from door");
         }
     }
 }

And I've dragged the door prefab into the appropriate box in the Inspector for the IsPlayerNextToDoor script attached to the player.

But when I go to check this in my game, where I have three instances of my door prefab, it only works on one of them and then only once at that, and the debug text never changes again after the first time when it confirms I'm next to the one particular door in the game it works on.

$$anonymous$$y thinking is that the debug text should keep switch between the two states/sentences as I move in and out of range of the door, and that this code should work on every door I approach too, but it's obviously not doing quite what I expected it to.

Any idea what might be up here?

Is there maybe something silly I might have done that would make this presumably otherwise correct code not work as intended in my case specifically?

avatar image CB-TV · Mar 12, 2014 at 05:19 PM 0
Share

For me, it says:

'position' is not a member of 'UnityEngine.Vector3'.

I have a variable in there that is currently empty but will be filled in-game with a rigidbody.

avatar image
5

Answer by efge · Mar 17, 2010 at 09:52 PM

Look at the reference for Vector3.sqrMagnitude (with example).

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
3

Answer by Zootie · May 05, 2010 at 07:21 PM

There is also Vector3.magnitude...

but what is the difference between using Vector3.Distance(a,b) and Vector3.magnitude(a-b)? Does one compute faster than the other?

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 Mike 3 · May 05, 2010 at 07:34 PM 1
Share

It'd be (a-b).magnitude for the latter one - which involves creating a new vector3 just for finding the magnitude, which Distance skips. $$anonymous$$agnitude is great for calculating the length of a single vector though

avatar image
2

Answer by sandhillceltic · Jun 25, 2013 at 03:49 PM

A more mathematical approach, you could use the Pythagorean Theorem and calculate the hypotenuse using the right triangle with the grid units in unity. So, the square root of (delta)X^2 + (delta)Z^2 = flatdistance (this is a var) and then... square root of flatdistance^2 + (delta)Y^2 = distance between the two points

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 Graham-Dunnett ♦♦ · Jun 25, 2013 at 03:50 PM 0
Share

What @sandhillceltic said, plus the advice that the transform attached to each gameobject has a position member, which you'll need.

avatar image
0

Answer by Verontrax · Jul 15, 2016 at 05:38 AM

My suggestion is to avoid taking the square root of anything.

I would do this buy finding the distance of characters x and y position from target and squaring each one and add them together.

(Yc - Ye)^2 + (Xc - Xe)^2 = D^2 , Where Xc and Yc are your characters position. amd Ye, Xe is the enemies and/or targets position.

for comparing it if it is in range, use range of whatever R, display it as R, but internally it should be stored as R^2 to compare to D^2. Thus avoiding any complicated math.

if you are using 3d graph you need to ad deltaZ^2 to D^2 as well (delataZ = Zc - Ze)

Why do I suggest not using the square root, first. you can use the distance squared just as easily as the you could use the actual distance and taking the square root of a number is slow... I mean it only takes around O(log n) (or better depending on what method is used) but to do better you need complicated math which might not actually make it any faster (depending on the processor being used) where as keeping the distance as itself squared gets rid of an unnecessary object and takes O(1) time :)

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
  • 1
  • 2
  • ›

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

13 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Move a Person to a point / Repeat a function called from another script? 1 Answer

Display the speed of a Game Object in MPH 1 Answer

"Can't find namespace" - accessing Javascript from C# (or C# from Javascript) 3 Answers

Reload Level on Collision 4 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