# Create semi-random guesses

I don’t like the Random.Range function as used in the lectures. It doesn’t feel natural to me that a number wizard would pick a completely random number. Alternatively I wished to create a wizard who would pick in a range around the middle number (+ or - 15%).

Simply getting your guess and adding or detracting 15 percent won’t do. (F.E. a guess of 900 might result in a number higher than 1000).

I found a solution using fmath.lerp. First use Random.Range function to create a random number between 0.35 and 0.65 (0.50 +/- 0.15).

Then you will need to use Mathf.lerp. This function takes three inputs (min, max, and step). Step (officially called interpolation) is a number between 0 and 1 and determines how for you move from min to max. If step has the value 1, Mathf.lerp will return the max value, while 0 would be the minimum value. The value 0.5 would, you guessed it, result in the point right in the middle of min and max. Confused? See this link for unity’s short tutorial on fmath.lerp.

Now, there is one final problem. Mathf.lerp returns a float so you will need a simple converter to make this float into an integer. There is a simple build in function for this.

My final code worked like a charm and looked like this:
guess = Convert.ToUInt16
(Mathf.Lerp (min, max, UnityEngine.Random.Range (0.35f, 0.65f)));

For the sake of illustration I wrote a longer version of this code that does things step by step. Variables would need to be declared first for this code to work.

interpolation= UnityEngine.Random.Range (0.35f, 0.65f);
guessFloat = Mathf.Lerp (min, max, interpolation);
guess = Convert.ToUInt16(guessFloat);

1 Like