- Home /
I don't understand the random number generator output.
I'm trying to generate a random angle between around 30 and 150 (for a brick breaker game, the ball leaving the paddle at the start). This is the code I'm using:
void Start () {
// Calculates a random angle for the ball to leave the paddle
angleOfExit = Random.Range(30, 150);
// Calculates the X and Z components of the ball's speed
speedX = MasterSpeed * Mathf.Cos(angleOfExit) * Time.deltaTime;
speedZ = MasterSpeed * Mathf.Sin(angleOfExit) * Time.deltaTime;
speedX = Mathf.Abs(speedX);
speedZ = Mathf.Abs(speedZ);
}
MasterSpeed is a public variable for the speed so I only need to change one value. I'm using Random.Range to get the angle, and then trig to calculate the X and Z components of the speed, which I use in Update() to make the ball move.
When I run the game, though, sometimes the ball moves off at a really shallow angle, definitely below 30 degrees, and I can't figure out why.
$$anonymous$$athf.Cos
and $$anonymous$$athf.Sin
take an angle in radians, not degrees
Answer by Benproductions1 · Jun 13, 2013 at 05:30 AM
Hello
Your problem is that you are using degrees in your Mathf
functions, but when looking at the Documentation, it clearly states that it takes an argument in radians.
Use either the Mathf.Deg2Rad
to convert an angle in degrees to radians, or just use radians directly :)
Hope this helps,
Benproductions1
guess I missed that, thanks! I should probably read the documentation in a bit more detail, huh
For the future you can remember that almost all math libraries in almost all languages uses radians
Your answer
![](https://koobas.hobune.stream/wayback/20220613104107im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Random.Range(..) not working 1 Answer
I want gameobjects to move randomly on screen without overlapping.` 2 Answers
Random Speed to an Object Rotation 0 Answers
Random.Range Vector3 2 Answers