- Home /
Snap a object position and direction
Is there a way to snap a object position and direction?
For example, there are two sticks. When they are in a range, they are snapped position and direction. Finally they become like one pole.
Thanks.
Answer by clunk47 · Sep 29, 2013 at 05:26 PM
I get an array of all transforms on awake, then create a generic list of specific transforms with the same name, then duplicate that list, so you can compare the distance between each object. In this C# example, once poles are in range of one another, they move toward one another until they are snapped into one another's position. For testing I created a few cubes and scaled them to look like "sticks" or "poles", then I created an empty gameObject for each stick, then set the empty on TOP of half the poles, and on BOTTOM of the other half, then made the empty the parent of it's stick, and named each parent empty "pole" to work with my example. You'll need to do this for the top on some and bottom on others so the pivot points snap together. This is a really small and simple example I came up with quickly, just to get you started. Break down the code and look up each thing that you may not understand in the Unity Script Reference.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
float range = 1.0f;
float moveSpeed = 0.25f;
Object[] transforms;
List<Transform> poles;
List<Transform> polesCompare;
void Awake()
{
poles = new List<Transform>();
polesCompare = new List<Transform>();
transforms = Object.FindObjectsOfType(typeof(Transform));
foreach(Transform t in transforms)
{
if(t.gameObject.name == "pole")
{
poles.Add (t);
polesCompare.Add (t);
}
}
}
void Update()
{
if(poles.Count > 0)
{
foreach(Transform p in poles)
{
foreach(Transform pc in polesCompare)
{
float dist = Vector3.Distance(p.position, pc.position);
if(dist <= range)
p.position = pc.position;
}
}
}
}
}
Hi @clunk47, do you know some package in Unity Asset Store that includes this "Snap function" for HTC Vive controls?
Very grateful in advance for your advice.