Search Unity

How to snap pivot points of gameobjects to components of an object

Discussion in 'Getting Started' started by Loquinette, Dec 22, 2015.

  1. Loquinette

    Loquinette

    Joined:
    Feb 13, 2014
    Posts:
    12
    Hi guys,

    First of all, I looked on the internet to find an answer to my question but I wasn't able to find one. And second of all I'm really new to programming, the only things I know are about 3D art =)

    So first of all, let me show you what I have for now and then what I'd like to do with that :

    As you can see in the image below, I created a plane in 3dsmax with 3 points/dummies names Point 1/2/3.



    I exported that object as an fbx and imported it in Unity.



    I now see the 3 different points in the hierarchy tab and I can see the different position of the 3 points when clicking on each of them.


    So I'd like to know what would be the best method to create the following behavior :
    Let's say I have a sphere, a cube and a cylinder somewhere in the scene. Once I click and drag the sphere on the plane (the one with the 3 "anchors" (Point1/2/3), once I release the click, I want the pivot point of the sphere to instantly snap to the according point (let's say Point1).
    Same would go for the cube that would go to Point2 etc.

    Thanks a lot.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Well, you just need a little loop that compares the sphere position to each of the anchor points, and calculates the distance (using Vector3.magnitude). Keep track of which one is closest. The code will look something like this:

    Code (CSharp):
    1. Vector3 bestPt = Vector3.zero;
    2. float bestDist = 1E6f;
    3. foreach (Vector3 pt in anchorPoints) {
    4.     float dist = (pt - sphere.transform.position).magnitude;
    5.     if (dist < bestDist) {
    6.         bestDist = dist;
    7.         bestPt = pt;
    8.     }
    9. }
    Then, you just set your sphere position to bestPt, and Bob's your uncle.
     
  3. Loquinette

    Loquinette

    Joined:
    Feb 13, 2014
    Posts:
    12
    Thanks a lot for the fast reply. I'll try that as soon as possible !