- Home /
Moving a non-player object in a random direction which bounces off other objects.
Hello!
Apologies for the title, I could not think of a good way to phrase my problem.
I am trying to make a space adventure game, where the player flies around asteroids. When the player starts the game, I want the asteroids to move in a random direction and then if it comes in contact with another asteroid it bounces off (I have already added a rigid body).
Once the asteroid is moving in that direction it must keep moving, and when it bounces it has to maintain the current speed it was, but in the opposite direction, like in space.
If anyone knows how to move a non-player object in a random direction when the game starts, please let me know.
Thanks for any help you can give!
Answer by Alanisaac · Dec 23, 2017 at 10:43 PM
Try this:
private Vector3 RandomVector(float min, float max) {
var x = Random.Range(min, max);
var y = Random.Range(min, max);
var z = Random.Range(min, max);
return new Vector3(x, y, z);
}
Usage:
void Start()
{
var rb = GetComponent<Rigidbody>();
rb.velocity = RandomVector(0f, 5f);
}
Answer by Chessnutter · Dec 23, 2017 at 10:57 PM
Worked pretty well! Had to modify the code a little because the game is 2d (sorry for not mentioning before). The asteroid only moved towards a more positive (x, y) so I changed
"rb.velocity = RandomVector(-5f, 5f);"
Thanks for all the help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612145129im_/https://answers.unity.com/themes/thub/images/avi.jpg)