How to move an object back and forth along a vector
I am new to Unity and coding in general, so I apologize if this question is poorly worded.
I am trying to move an object back-and-forth repetitively between two other objects. So far my thinking is this: 1) Determine the desired path between the two objects by calculating the equation of the line between them. (y = mx + b, b = 0) 2) use an oscillatory function like Sin(x) or Mathf.PingPong to modulate the value plugged in for x.
I would like some feedback on this idea, and if you know how to implement it that would also help! Is there an easier way to accomplish what I'm after?
Thanks
Answer by Jawchewa · Apr 28, 2017 at 06:29 AM
I would maybe consider using Vector3.Lerp() to move between the two objects. So something like this:
public class Lerper : MonoBehaviour {
Vector3 pointA = new Vector3(0, 0, 0);
Vector3 pointB = new Vector3(1, 1, 1);
void Update()
{
transform.position = Vector3.Lerp(pointA, pointB, Mathf.PingPong(Time.time, 1));
}
}
where pointA and pointB would be replaced with positions of your two gameObjects. There is also a Lerp function for Vector2, if you are in 2D. You might also need to do some additional math to control the speed, as Lerping will move your object at different speeds depending on the distance between the two points.
There's actually a lot of ways that you could go about implementing this, but this is just the first one I came up with off the top of my head.
More Details on Lerp here: https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
Thanks so much! This works perfectly. I have a different, general question which is unrelated that maybe you can help me with. For some reason when I hit "play" in my game, it seems that some of the scripts that affect game object motion are initialized, while others need to be un-checked and re-checked in the Unity editor in order to start working. Do you have any idea why this might be? Not sure if it's a common issue or not.
Sorry., I don't think I've seen that issue before, so, I have no idea how to solve it. $$anonymous$$aybe post a new question with more details to see if anyone else has any wisdom about that problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220612120824im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Angle between two Vectors split up into x,y,z components 0 Answers
Unity 2d make four directions (Up, Down, Right, Left. like RPG games) GUI buttons. Please help me. 1 Answer
How to spawn in precise interval for moving objects 0 Answers
Object heading towards mouse click/ touch position, script improvement. 1 Answer