# How to make my Object Zig Zag

I have an object in 3D space with a certain height (y) component that I wish to remain constant.

The object is a rigidbody, kinematic, affected by gravity and a trigger. So I tried this method following a similar StackOverflow answer:

public class ZigZagSun : MonoBehaviour
{
private Vector3 pos1 = new Vector3(0f, 1.1f, 0);
public float speed = 1.0f;
public float amplitude = 8.0f;
float t = 0f;
//resets position of the ZigZagSun
void Awake()
{
transform.position = pos1;
}
// moves object from pos1 to pos 2
void Update()
{
pos1.x = amplitude * Mathf.Cos(t);
pos1.y += speed * Time.deltaTime;
t += Time.deltaTime;
}
}


However instead of moving my Object remains still in space at (0,1,0) I am wondering what exactly it is that I have done wrong? is it to do with the object being static?

• Is update() actually being called? Is Time.deltaTime = 0 ? – mythos Dec 16 '15 at 4:30
• The code you've shown never actually tells the Rigidbody to move toward pos1 in the next FixedUpdate. It starts there in Awake, but Awake is only called once. Have you left out some code in what you've shown here? – DMGregory Dec 16 '15 at 5:21
• Yeah the code doesn't move the gameobject. Notice you set the transform.position in Awake, then you never move it again. – jgallant Dec 16 '15 at 12:50

Did you forget to update the position on each frame? Something like this should do it:

void Update()
{
pos1.x = amplitude * Mathf.Cos(t);
pos1.y += speed * Time.deltaTime;
t += Time.deltaTime;
transform.position = pos1;
}


When you call transform.position = pos1; you set the transform to a copy of the current values of pos1, not to a reference. Changing pos1 afterwards doesn't do anything.

To move the object, either write the changed position back to the transform component with transform.position = pos1; or even better just use transform.Translate:

void Update()
{
transform.Translate( new Vector3 (
amplitude * Mathf.Cos(t),
speed * Time.deltaTime,
0.0f
));
t += Time.deltaTime;
}


Note: this makes the object move in a cos(t)² curve, not a cos(t) curve, but I wanted to keep it simple to show you the concept.