How to make an object move in a zigzag using lerp and pingpong

I’m trying to make my object go towards another object by using vector3.lerp and making it follow a zigzag path using mathf.pingpong. However whenever I do this it just stays in one position going up and down.

private Vector3 originalPos;
public Vector3 desiredPos;
public float zigzagspeed;
public float zigzagdistance;
private float origypos;
public float speed;
// Use this for initialization
void Start () {
	originalPos=transform.position;
	origypos = originalPos.y;
}

// Update is called once per frame
void Update () 
{
	//zigzag
	originalPos = new Vector3(originalPos.x , origypos + Mathf.PingPong(Time.time * zigzagspeed, zigzagdistance), 0);
	//move object to target
	transform.position=Vector3.Lerp(originalPos, desiredPos, Time.deltaTime*speed);

}

}

2 Answers

2

Your Lerp calculation will only ever return one result, so the object stays in that one position. You need to factor in where the object currently is :

transform.position=Vector3.Lerp(transform.position, desiredPos, Time.deltaTime*speed);

This is not the best way to do what you’re trying. But to fix this method I would suggest lerping the object to the desired position using the original Y-value, then modifying the Y-value of the transform with the PingPong :

void Update ()
{
	Vector3 movePos;
	//move object to target
	Vector3 basePos = new Vector3( transform.position.x, originalPos.y, transform.position.z );
	movePos=Vector3.Lerp(basePos, desiredPos, Time.deltaTime*speed);
	//zigzag
	movePos = new Vector3(movePos.x , originalPos.y + (zigzagdistance * (Mathf.PingPong(Time.time * zigzagspeed)), movePos.z);
	transform.position = movePos;
}

Thanks, it worked nicely. For future reference, what's a better way of doing this?

Check out this Asset for Zig Zag movement.

ZigZag Endless Runner - Complete Game Template