How to make object move forward and up simultaneously
I have an object like a hot air balloon spawned and moving forward, now I want that object to rise (go up or down) at the same time, but when I try to use both lines of code below it only accepts one of the directions and ignores the other. How can I make the object move from left to right and up at the same time? My search here found related question with answer to use Quaternion.LookRotation but I don't want to rotate my character (spawned objects) I just need (as example) a hot air balloon going sideways with the wind and then goes up higher using a set speed. Is LookRotation really the way?
GetComponent<Rigidbody>().velocity = Vector3.forward * speed;
GetComponent<Rigidbody>().velocity = Vector3.up* speed;
Answer by NoseKills · Jan 01, 2016 at 05:12 PM
So .velocity is a vector. It has components .x .y and .z to indicate movement in all directions in 3D space. What you are doing now is setting that vector to 2 different values one after the other and only the latter applies like you have noticed
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 1)* speed;
GetComponent<Rigidbody>().velocity = new Vector3(0, 1, 0) * speed;
What you want to do is set the value to be a vector that has the correct values for each component
Vector3 v = (Vector3.up + Vector3.forward) * speed;
GetComponent<Rigidbody>().velocity = v;
// or
GetComponent<Rigidbody>().velocity = new Vector3(0, speed, speed);
write it any way you want as long as you set .y and .z to the value you want. Also not that the way you are doing it would result in the balloon traveling faster when it's going up or down since the length of a vector (0,speed,speed) is longer than that of (0,0,speed). To solve that you should normalize the vector (make its length 1) before multiplying it with speed
Vector3 v = (Vector3.up + Vector3.forward).normalized * speed;
GetComponent<Rigidbody>().velocity = v;