6.2 Random Float

So far we’ve discussed random whole numbers. But you will often need floating point values. These are provided by the function RandomF(). This function will return a value between 0 and 1 by default, but it will also accept arguments. RandomF(3) will return a value between 0 and 3. RandomF(-1.3, 2.5) returns one between -1.3 and 2.5.

These functions are often used to show an object on a random position. Like so:

 
Circle c; 
 
c.pos.x = RandomF(-D.w(), D.w()); 
c.pos.y = RandomF(-D.h(), D.h());  
5

In the example above, we won’t even pass actual numbers to the function RandomF(). Instead, we let our application decide. The width and height of the screen are not the same on every device. By asking the engine about it, we will always end up with the correct values.

Exercise
Create an application which shows a circle on the screen. Every time the space bar is pressed, you change the circle’s position.

Exercise
Create an application with a small rectangle on the screen. Assign a new position every second.

Exercise
Starting from the previous exercise, add an int ‘score’ equal to zero. Draw this score somewhere on the screen. When the left mouse button is pressed, check if the mouse pointer is on top of the rectangle. If it is, increase the score by one.

Exercise
(A bit harder) With every score increase, the position of the rectangle should change a bit faster.