user12285218
user12285218

Reputation:

Move an object up/down slowly in Unity?

I am trying to move my object up and down (Y-axis) slowly, it works but unfortunately the object starts moving up/down from a different position. How do I make sure that it starts moving up and down from a given position say Y=10.25f?

float speed = 2f;
float height = 0.05f;

void Update()
{
    Vector3 pos = transform.position;

    float newY = Mathf.Sin(Time.time * speed);

    newY = newY*height;

    transform.position = new Vector3(pos.x, newY, pos.z);
}

Upvotes: 0

Views: 3783

Answers (1)

Kris Krej
Kris Krej

Reputation: 26

If I've understood you well, you should just add start Y position to newY for example this way:

float speed = 2f;
float height = 0.05f;
float startY = 10.25f;

void Update(){
    var pos = transform.position;
    var newY = startY + height*Mathf.Sin(Time.time * speed);
    transform.position = new Vector3(pos.x, newY, pos.z);
}

Upvotes: 1

Related Questions