Using mathf.Sin() to move an object

I have an object which I want to move left and right and I am using the following code to do so

xPos= Mathf.Sin(Time.time);
		transform.position = new Vector3(xPos, 0, 0);

This puts the object in the center of the world and it does move it left and right but I want it to stay in its current position and then move. If the transform.position.x is at 10, how can I move it so it goes to 11 and then to 9? I have tried

xPos += transform.position.x;

to get the current position but then the behavior completely changes.

Hey There,

Your object goes to the centre of the world because you set its position based on Sin [ a range of -1 to 1]. All you need to do is save an offset. Take a look at the code below.

private Vector3 _startPosition;

void Start () 
    _startPosition = transform.position;

void Update()
     transform.position = _startPosition + new Vector3(Mathf.Sin(Time.time), 0.0f, 0.0f);

We save the objects start position so that it always moves from that point and not the centre of the world.

If you don’t want to cache it’s position you can do this

  _newPosition = transform.position;
  _newPosition .x += Mathf.Sin(Time.time) * Time.deltaTime;
  transform.position = _newPosition ;

The reason “the behaviour completely changes” when using += is because you are adding anywhere between -1 and 1 unites every frame (60 time per second). This will make your object shoot across the screen. You can use Delta Time as a scaler to control it’s speed (it’s also a good rule of thumb to use delta time on all movement code).


public float speedUpDown = 1;
public float distanceUpDown = 1;

void Update () 
		Vector3 mov = new Vector3 (transform.position.x, Mathf.Sin(speedUpDown * Time.time) * distanceUpDown, transform.position.z);
		transform.position = mov;

You can control the speed of oscillation by introducing a “time” variable that controls the time period i.e. the time taken to complete left and right motion:

public float timePeriod = 2;
public float height = 30f;

private float timeSinceStart;

private Vector3 pivot;

private void Start()
    pivot = transform.position;
    height /= 2;
    timeSinceStart = (3 * timePeriod) / 4;

void Update()
    Vector3 nextPos = transform.position;
    nextPos.y = pivot.y + height + height * Mathf.Sin(((Mathf.PI * 2) / timePeriod) * timeSinceStart);

    timeSinceStart += Time.deltaTime;
    transform.position = nextPos;

This is more flexible than using a “speed” variable

Plus, the code makes sure that the object always starts at the initial position. The reason timeSinceStart is used is to offset the time value so that the very first frame the Mathf.Sin() function evaluates to ‘-1’, and the object starts at the initial position, instead of halfway between the beginning and the destination.

Feel free to ask me doubts or inform me about bugs :slight_smile: