- Home /
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.
Please suggest me a solution.
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.
Answer by robertbu · Mar 11, 2014 at 04:18 PM
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 am Facing Problem with the above mentioned code ... 1-I have tried it on bottles which i want to translate "To and Fro " $$anonymous$$otion in my game view and player can shoot 2-When i add this script to bottles , bottles position is infinite or else where in the given bench on my model
Answer by screenname_taken · Mar 11, 2014 at 04:41 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613135946im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How the heck does Mathf.Lerp work? 2 Answers
Can someone help me to understand what vector3.lerp does and can be used for 2 Answers
How to move character a certain amount? 1 Answer
Vector3.Lerp move weapon up to players face 2 Answers
Lerping Issue 1 Answer