Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Shortest Distance between two objects

Discussion in 'Scripting' started by shs2410, Jul 24, 2021.

  1. shs2410

    shs2410

    Joined:
    Jul 13, 2021
    Posts:
    15
    How do I find the shortest distance between one large object and one small object(for eg. a wall and a cube)? How do I show a line connecting the points that make up the shortest distance between them?

    I had read that you need to use closestpointsonbounds but I am unclear on how to do that. Can someone help me?
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    ClosestPointOnBounds is not what you are looking for I don't think, that uses a collider and a point, not for example two colliders. The task you have is very difficult to calculate in terms of speed.

    What do you need this information for? Maybe there's an easier way
     
  3. shs2410

    shs2410

    Joined:
    Jul 13, 2021
    Posts:
    15
    I need to set the distance between two objects. I have tried using vector3.distance but it sets the distance from the center of the wall. For example, the cube needs to be at a distance of 25m from the wall. So the shortest distance between the cube and the wall has to be 25. And I want a line showing a connection between both objects stating the distance. I hope this makes sense.
     
  4. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Hmm, depending on the requirements, you could do the following:
    If your cube and wall are aligned, so one of the cube faces is parallel to the wall, then that's simple, your whole distance between the centers on one axis (the one perpendicular to the walls and the cubes face) will be the half width of your cube, the half width of the wall and your desired distance. So if it's a 1x1x1 cube and the wall is 1m thick, then it's 0.5m + 0.5m + 25m = 26m on that axis.
    If this is enough, I won't write more
     
  5. shs2410

    shs2410

    Joined:
    Jul 13, 2021
    Posts:
    15
    I'm not sure I understand what you want me to do. How am I supposed to set the distance of the cube? Also, the example you gave with the objects being aligned might not always be the case in my project.