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

Question How to snap objects into place?

Discussion in 'VR' started by chrysw, Mar 21, 2021.

  1. chrysw

    chrysw

    Joined:
    Feb 10, 2018
    Posts:
    1
    I'm currently doing a school project that lets users do breadboarding in VR. One thing I'd like to do is for users to select and place components in the right places on a breadboard, like this (skip to 8:25):



    I currently have a model of a breadboard and can grab the electronics components (using Distance Grabbable script from Oculus samples). The model of the breadboard has individual components for every single pin-out. Given this, what's a good way for me to snap components into the pin-outs? I'm quite new to unity dev and VR development, so any help here would be great.

    model pic: https://imgur.com/a/HsZB3zV

    Thanks!
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Snapping into place takes a bit of math. The basic idea is:
    1. Get the distance between the component position and the first column of holes, along (say) just the X axis: dist = part.x - firstHole.x;
    2. Divide this by the hole spacing, round it, and then multiply by the hole spacing again. This rounds to the nearest multiple of the hole spacing: dist = Mathf.Round(dist / holeSpacing) * holeSpacing;
    3. Add the position of the first column of holes back in: part.x = dist + firstHole.x;
    You will probably need to do that for Z as well. And do all this when the part is released (when I presume you are also going to set the Y position to the proper value for an inserted part).
     
    chrysw likes this.