- Home /
How to switch 2 objects' positions gradually?
GameObject o1, o2;
Vector3 o1Position, o2Position;
bool access = false;
float speed = 0.50f;
void Update()
{
if ( /* it's necessary to switch these objects */ )
{
o1Position = o1.transform.position;
o2Position = o2.transform.position;
access = true;
}
if(access)
{
o1.transform.position = Vector3.Lerp(o1Position, o2Position, speed);
o2.transform.position = Vector3.Lerp(o2Position, o1Position, speed);
if(o1.transform.position == o2Position)
{
access = false;
}
}
}
I try Lerp as you can see above but that only moves my objects half way to their destinations and they end up sharing the same positions. Is there another way to switch their positions slowly or how can I fix one? I played around with speed variable but it didn't help. Thanks in advance.
Answer by robertbu · Feb 03, 2014 at 03:43 PM
If you don't want eased movement at the end, do:
o1.transform.position = Vector3.MoveTowards(o1.transform.position, o2Position, speed * Time.deltaTime);
o2.transform.position = Vector3.MoveTowards(o2.transform.position, o1Position, speed * Time.deltaTime);
'speed' will be units per second for movement.
No, that's not what I was asking. Neither o1 nor o2 reaches their destination. For example : if o2Position is (2,0,0) and o1 is at (1,0,0), o1 stops at (1.5, 0, 0).
Yes I know what is happening. The problem is that your 'speed' parameter is set to 0.5f. That means that your two objects will immediately jump to the midpoint between the two positions. $$anonymous$$aking the change I recommended will fix the problem. Alternately you could implement a timer. Lerp()'s third parameter ranges from 0.0 to 1.0. You would then have as your third parameter 'timer/totalTime'.
I'm sorry but that didn't change a thing. Whatever the speed value is, they're not going more than halfway.
I'd need to see your updated code to figure out what is wrong, but the two lines I posted are right. Here is a class based on your code above along with my two lines. It works fine.
using UnityEngine;
using System.Collections;
public class Bug25d : $$anonymous$$onoBehaviour
{
public GameObject o1;
public GameObject o2;
Vector3 o1Position, o2Position;
bool access = false;
float speed = 0.50f;
void Update() {
if (!access && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space)) {
o1Position = o1.transform.position;
o2Position = o2.transform.position;
access = true;
}
if (access) {
o1.transform.position = Vector3.$$anonymous$$oveTowards(o1.transform.position, o2Position, speed * Time.deltaTime);
o2.transform.position = Vector3.$$anonymous$$oveTowards(o2.transform.position, o1Position, speed * Time.deltaTime);
if(o1.transform.position == o2Position && o2.transform.position == o1Position) {
access = false;
}
}
}
}
I did not see how you initialized 01 and 02. I initialized them through drag and drop. The two objects switch places when hte space bar is pressed.
Thanks, you've done your part. Issue with my script must be something else.