- Home /
how to have object fall using random speed
I have a object falling down slowly which is fine, however, while it is falling, it's also moving left and right. I instantiate this falling object so hopefully when it move left and right, it moves all in random speed. here is my script
void Start ()
{
fall = 2f;
tempVal = transform.position.x;
tempPos = transform.position;
}
// Update is called once per frame
void Update ()
{
tempPos.x = tempVal + amplitude * Mathf.Sin (speed * Time.time);
tempPos.x = Random.Range (-4, 4);
transform.position = tempPos;
Vector2 position = transform.position;
tempPos = new Vector2 (position.x, position.y - fall * Time.deltaTime);
transform.position = position;
Random.Range made my object moving left and right randomly but it's moving too fast. how do i make it move left and right, nice and smooth in random speed
Notice that in line 11. you set tempPos.x, and in line 12. you change it again, completely disregarding what you did in line 11. Also, in line 11. Random.Range will set the position to some random value between -4 and 4 EVERY FRA$$anonymous$$E. So 60 times per second, it will jump around like crazy.
There are a few ways to get "random velocity" in this case.
1) You could attach a RigidBody to your object, which now gives you things like "velocity" so that the physics engine moves the object and "AddForce" so that you can apply force to cause velocity to change smoothly.
2) You could make a new variable, "float theta = 0f;" and "float thetaSpeed = 0f;" and have thetaSpeed change every frame randomly and have do "theta += thetaSpeed Time.deltaTime" and use "tempPos.x = tempVal + amplitude $$anonymous$$athf.Sin(theta);".
Also, when program$$anonymous$$g, try to always give meaningful variable names ins$$anonymous$$d of "tempSomething". For example, it looks like tempVal doesn't change after Start. So call it "startPosX" ins$$anonymous$$d. Or "currentPos" ins$$anonymous$$d of "tempPos".
Good luck.
ahh i see. thanks for the info. i'm still new to scripting and I've been throwing in random script to test things out >.< but no luck in succeeding. Thanks a lot though, i'll give it a shot
Your answer
Follow this Question
Related Questions
Object Spawner acts really badly, 0 Answers
Network: Random spawn 1 Answer
Random.Range changed in Unity 5? 2 Answers
How To Random Range a Float? 2 Answers