1
\$\begingroup\$

Any idea if there is a way I can make a gameobject snap to something when it gets close to it? Like drag a cube around and when it gets close to something then snap to it.

\$\endgroup\$
  • 2
    \$\begingroup\$ I downvoted because this question does not show research effort and no attempt was made \$\endgroup\$ – Hellium Nov 17 '17 at 14:47
  • \$\begingroup\$ I upvoted it to counter the downvote, because I tried searching, and it took a while to find anything, as snapping defaults to result for snapping in the scene editor, after about 5 or 6 tries, I still only found weak unclear references. \$\endgroup\$ – Dan Violet Sagmiller Nov 17 '17 at 18:20
1
\$\begingroup\$

Any position you want it to snap to as it gets close, you could do something like this (Psuedo code)

(assuming you already have code to move the object) - Create a parent object, that contains the script SnapOn.
- That parent object is what moves.
- The child object should have the visible element, cube for instance. - In the SnapOn Script, - - The anchors are used to define positions the object can snap to - - The "movable" is the child object that actually renders. - - SnapDistance is how far away to snap.

class SnapOn {
public Transform[] anchors;
public Transform movable;
public float SnapDistance = 1f;

Update() {
  // first we find the closest object, but looping through all and saving the shortest distance (and position)
  var distance = float.max;
  var point = vector3.zero;
  foreach(var anchor in anchors)
  {
    var d = Vector3.Distance(transform.position, anchor.position);
    if (d < distance) 
    {
      distance = d;
      point = anchor.position;
    }
  }

  // now we decide if there is anything it should snap to.
  if (distance > SnapDistance) // too far, keep renderable with movable.
  {
    movable.position = transform.position;
  }
  else // position is close enough to snap point put it there.
  {
    movable.position = point;
  }
}

if you neglect to track the moving position separate from where to render the object, the instance you are on a snap on to a position, you will unlikely be able to move the object far enough in a single frame to allow it to "unsnap"

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.