snap object to another object
how do I snap Cube1 to Cube2 when they are very close to each other? can it be used with rigidbody objects? grateful if anyone could help in c#
eg: when Cube1 gets close to Cube2, Cube1 will automatically move towards Cube2 and stays nicely beside Cube2. hope it helps
Do you want them to snap in edit-mode? If so take a look at this:
no. I'm trying to snap objects in game and not in edit
Answer by alexanderameye · Nov 18, 2016 at 08:30 AM
If these objects are simple cubes with all the same size, you first need to check whether or not the distance between the two objects is < some value. You can achieve this with Vector3.Distance.
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
so something with this structure
if(Vector3.Distance < 5.0f) snap
Then you want the objects to snap, this is a bit more tricky. With simple cubes, you could try this logic:
if the distance between the two cubes is small enough --> cube2.position.x = cube1.position.x + cube1.localscale.x --> cube2.position.y = cube1.position.y --> cube2.position.z = cube.position.z
OR
look at this tutorial
http://catlikecoding.com/unity/tutorials/frames-per-second/
where they also make some objects snap to one another
will try out the cube snapping logic out. regarding the tutorial, seems like they are using force to move and snap the balls together. I'm thinking, will snapping work using raycast?
Answer by azizmohseny · Oct 03, 2018 at 04:48 PM
How to snapping 2D Ui to another 2D Ui when they ar very near to each other?
Your answer
![](https://koobas.hobune.stream/wayback/20220612100840im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Need help with snapping Prefab assets to grid in game 2 Answers
Swipe to rotate an object and when it reach 30° snap it to 90° 0 Answers
Unity Snap settings. moving slightlty wrong 1 Answer
NullReferenceException: Object reference not set to an instance of an object 2 Answers
Snapping using kinect v2 sdk 1 Answer