In my game I have some powerUps which are gain when enemy is killed. Is there a proper way to come up with random numbers?

here is what i am thinking:

double rand = Math.random();

if(if (rand < .001){ // 1 in 1000 chance
if(rand < .20){   // 1 in 5 chance

is there a better way?

  • 3
    \$\begingroup\$ What would you like to be better about it? \$\endgroup\$ – Seth Battin Oct 3 '13 at 4:34
  • \$\begingroup\$ ...that what i am asking in thread. you just rewrote my question. if you dont know than just say 'idk'. \$\endgroup\$ – user1924249 Oct 3 '13 at 4:51
  • \$\begingroup\$ You are asking if there is a better way to get a random number than by getting a random number... \$\endgroup\$ – Chewy Gumball Oct 3 '13 at 4:53
  • 2
    \$\begingroup\$ I was trying to get you to improve your question. What is it about your current method that you think needs to be improved? What makes you think you need to do something else? If you have no way to answer that, then your question is polling for opinions, which is outside the scope of the site. This is a site for answerable questions; not for taking polls. And posting "idk" as an answer is always wrong. \$\endgroup\$ – Seth Battin Oct 3 '13 at 5:05
  • \$\begingroup\$ Math.Random isn't the best way to go if you need a lot of random numbers in a short period of time, but if this only happens once in a while this isn't a bad solution. \$\endgroup\$ – Thomas Oct 3 '13 at 6:20

I'm new to gamedev.se so I can't comment yet, but I think what you're trying to ask is

How does one get a boolean answer with a certain probability?

If that's the case, then it's easy. You just do exactly what you're doing already. Except that you're going to want to put it into a function if you plan on having more than a couple of powerups:

// Returns true <percent> of the time.
public static bool Chance(double percent)
    percent /= 100;
    return Math.Random() < percent;
  • \$\begingroup\$ perfect, this is what i was looking for. thanks alot. \$\endgroup\$ – user1924249 Oct 3 '13 at 6:23

Your Answer

