| Getting Started - Random Numbers |
|
|
|
| Written by Smash |
| Monday, 27 July 2009 00:21 |
How do I get Random Numbers in ActionScript 3.0?We suggest you first view the video tutorial on the bottom of this page for a better understanding of this article. Getting random numbers in actionscript 3.0 is kind of a pain compared to some programming languages, but once you get used to it, it is easy. Lets see how to code a random number that is between 0 and 100;
Here we use the Math.Random() function to create a random number, now the problem with this function i that it gives you a number between 0 and 1, for example 0.213879532. How do we get around this? We multiply the outcome by a whole number, this whole number will be the max possible outcome. This can still be a problem because our number is not a whole number, it still have decimals in it. To get around this fact we must use one of a few Math functions to round the decimals to a whole number. These are the functions we can use and there we go, all the random numbers we could ever want. In the video I explain how to create a simple function to return a random number within a specified range do create that function we would use this code This function is very handy for big projects, or you could even put it in a class so you would only have to write it once, I will be covering classes in one of the next tutorials. Then finally in the video we use random numbers to randomly place our movieclip on the stage. This would be useful in a shooting game of some sort, so that every time you shoot the target, it is randomly placed somewhere else. There are many uses for random numbers try expirimenting! |



