- Home /
How do I swap two objects without them colliding ?
So I have two cubes, (1,0,0) and (-1,0,0). If I use Vector3.Slerp() on these two cubes. This works fine.
However if the cubes are away from the origin, lets say the new positions are (3,0,0) and (1,0,0). Slerp no longer behaves as I think it should do.
So two questions. How do I get what I want done? And whats really going on here ?
I've posted my working code below. Feel free to comment, I'm super new to unity c#.
public float timeToComplete;
float startTime;
Vector3 startPosition, endPosition;
public GameObject go1;
public GameObject go2;
Vector3 po1, po2;
GameObject go;
void Start(){
startTime = Time.time;
po1 = go1.transform.position;
po2 = go2.transform.position;
}
// Update is called once per frame
void Update () {
var d = (Time.time - startTime) / timeToComplete;
go1.transform.position = Vector3.Slerp (po1, po2, d);
go2.transform.position = Vector3.Slerp (po2, po1, d);
var tep2 = go2.transform.position;
tep2.z *= -1;
go2.transform.position = tep2;
}
Answer by arjunachatz · Feb 19, 2018 at 04:14 AM
Never mind .. answered my own question here. The solution was to bring the center point of the box to the center of the world. Then use slerp around the wold origin. And at the end of the calculate set the objects back into the original centered positions. Changing origins is always the answer .. More code
public float timeToComplete;
float startTime;
Vector3 startPosition, endPosition;
public GameObject go1;
public GameObject go2;
Vector3 cpo1, cpo2, c;
GameObject go;
void Start(){
startTime = Time.time;
Vector3 po1, po2;
po1 = go1.transform.position;
po2 = go2.transform.position;
c = (po1 + po2) * 0.5f;
cpo1 = po1 - c;
cpo2 = po2 - c;
}
// Update is called once per frame
void LateUpdate () {
var d = (Time.time - startTime) / timeToComplete;
go1.transform.position = Vector3.Slerp (cpo1, cpo2, d) + c;
go2.transform.position = Vector3.Slerp (cpo2, cpo1, d) + c;
var tep2 = go2.transform.position;
tep2.z *= -1;
go2.transform.position = tep2;
}
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Quaternion Rotation Smooth 1 Answer
Distribute terrain in zones 3 Answers
Quaternion.slerp only on the y axis 1 Answer
Lerp Rotation C# 3 Answers