- Home /
Snap to place
i am trying to make it so that if an object that im dragging around gets close to any empty Gameobject with the name "TopSnap" then it will move to the top of the object and if it gets close to anything names "BottomSnap" then it will move to the bottom. I will have a few cylinders with 2 empty game objects on it one will be the top snap and the other is the bottom snap.
Answer by EvilTak · Dec 06, 2014 at 04:47 PM
If you are using rigidbodies, you can create triggers in your empty gameobjects to represent the area in which the object will snap. Then add a script to them with the OnTriggerEnter function, in which make the position of the object which enters the trigger same as the empty gameobject in which it entered. Or if you are not using rigidbodies, each update check the sqrdistance between each object and the topsnap or bottomsnap gameobjects. If it is less than a certain value, then snap the object. Personally I prefer the first method, with kinetic rigidbodies and using rigidbody.MovePosition(). It is easier to implement and involves just half a dozen lines of code.
EDIT: Steps for first method:
Add any tag to your cylinders or gameObjects which you want to snap
Add a box collider or sphere collider to both TopSnap and BottomSnap objects, resize it to depict the area in which the object, on entering will be snapped. This can be any size you like.
Add rigidbodies to all gameObjects you want to snap and make sure they have a collider (collider should be on same transform as rigidbody).
void OnTriggerEnter(Collider other) { if(other.gameObject.CompareTag("the_tag_which_you_kept_earlier") { other.rigidbody.MovePosition(transform.position); } }
Attach the script to the TopSnap and BottomSnap gameObjects
Done!
Hay thanks for the reply but im a but rusty in unity do you think you could help?
Edited my answer to include steps. If it helped you please accept it.
Alright so i tried but nothing happens when they get close this is what i have done so far...
i made a tag and put it on my two cylinders then i made two empty game objects and named one topsnap and the other bottom snap then put both as a child of the cylinder then i added a sphere collider to both top and bottom snaps and i added a ridgid body on the cylinders along with a collider then i made the script and added it to top and bottom snaps then i tried and its not working so what have i done wrong?
Why have you put topsnap and bottomsnap as the children of a cylinder? Btw, the cylinders will have to enter the sphere collider (should have isTrigger marked as true) of topsnap or bottomsnap to get snapped.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
I made a better shader how do i fix[add _Shadow Strength]help???>Sorry that im asking for to much 1 Answer
Rotation Snapping is adding harmful floats! 1 Answer
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
Building in Unity 1 Answer