Search code examples
c#transformunity-game-enginegameobject

How can I swap the positions of two objects at different speeds, instead of an instant swap?


I have a script that currently swaps the position of 2 objects. The objects are the same size and shape so that when they swap positions, it's instant and you don't see them move toward the position. How can I make it so there is a movement speed when the two objects swap places, so that you can see them actually moving positions. I also need to figure out how to add a third object so that they all switch positions randomly. Something like this is my final goal: http://i249.photobucket.com/albums/gg240/OldNewby4507/shell-game-animated.gif

 using UnityEngine;
 using System.Collections;

 public class NewBehaviourScript : MonoBehaviour
 {

     public float movementSpeed = 10;
     public GameObject g1;
     public GameObject g2;
     public Vector3 vec1;
     public Vector3 vec2 = new Vector3(2F, 2F, 2F);
     public bool swapBack = false;

     void Start()
     {
         g1 = GameObject.Find("object1");
         g2 = GameObject.Find("object2");
         vec1 = new Vector3(g1.gameObject.transform.position.x, g1.gameObject.transform.position.y, g1.gameObject.transform.position.z);
         vec2 = new Vector3(g2.gameObject.transform.position.x, g2.gameObject.transform.position.y, g2.gameObject.transform.position.z);

     }

     void Update()
     {
         if (Input.GetMouseButtonDown(0))

         {
             vec1 = g1.gameObject.transform.position;
             vec2 = g2.gameObject.transform.position;
             g1.gameObject.transform.position = vec2;
             g2.gameObject.transform.position = vec1;
         }
     }
 }

right now my movementSpeed variable is unused.


Solution

  • You can Lerp the transition at difference rates, which is quite linear, if you would like you can also use Slerp or any of the other Vector3 methods.

    You can also use libraries that offer Tweening operations such as iTween amongst a bunch of other ones on the asset store which will take care of the transition for you.