# Moving two game objects in To and Fro motion continuously?

I have two Game objects that should move in To and Fro motion continuously.
Have tried this using ping pong but i couldn’t get smooth movement.
I have also tried this using vector3.lerp,but dint get the desired output.

Below is the code i tried using PingPong:

``````m_Bolt1X = m_bolt1.gameObject.transform.localPosition;
m_Bolt1X.x = Mathf.PingPong( Time.time * 1.0f, 1.2f ) - 1.1f;
m_bolt1.gameObject.transform.localPosition = m_Bolt1X;
m_Bolt2X = m_bolt2.gameObject.transform.localPosition;
m_Bolt2X.x = Mathf.PingPong( Time.time * 1.15f , 1.3f ) - 0.7f;
m_bolt2.gameObject.transform.localPosition = m_Bolt2X;
``````

Code using Vector3.Lerp:

``````_startPosition = m_bolt1.gameObject.transform.localPosition;
_endPosition = new Vector3(-1.5f,0.9271002f,0f );

m_bolt1.gameObject.transform.localPosition = Vector3.Lerp(_startPosition,_endPosition,Time.time * m_Speed);
if(Vector3.Distance(m_bolt1.gameObject.transform.localPosition,_endPosition) < 0.1f)
{
if(_startPosition.x == -1.5f)
{
_startPosition = m_bolt1.gameObject.transform.localPosition;
_endPosition = new Vector3(-0.5f,0.9271002f,0f );

}
if(_startPosition.x == -0.5f)
{
_startPosition = m_bolt1.gameObject.transform.localPosition;
_endPosition = new Vector3(-1.5f,0.9271002f,0f );
}
``````

Where m_bolt1 is one GO and m_bolt2 is second GO.
Have three positions A,B and C. GO 1 should move from B->A anb A->B and GO 2 from B->C and then C->B continuously.

Usually people are happy with a sinusoidal motion. Here is a bit of code that moves an object between to Vector3s. Put it on a Cube in a new scene to test. I’ve used defined Vector3 values, but you could modify the code to use the positions of two game objects.

``````#pragma strict

var Pos1 = Vector3(-4,0,0);
var Pos2 = Vector3(4,0,0);
var speed = 1.0;

function Update() {
var fraction = (Mathf.Sin(Time.time * speed) + 1.0) / 2.0;
transform.position = Vector3.Lerp(Pos1, Pos2, fraction);
}
``````

I did that for a scene of mine just a couple of days ago. Basically just a moving platform.
But i cheesed it out and made the movement in the animator panel. Just smoothed it out with the motion curves there.