Let's say that there is an X% chance that a character will shoot a target, or some other action. How do I determine if the action should be taken or not (how do I implement the percentage chance)?
\$\begingroup\$
\$\endgroup\$
3
-
1\$\begingroup\$ Please check these related questions to ensure your question is not already answered: gamedev.stackexchange.com/questions/54551/… gamedev.stackexchange.com/questions/32992/… gamedev.stackexchange.com/questions/59543/… gamedev.stackexchange.com/questions/16608/… \$\endgroup\$– HouseCommented Aug 8, 2014 at 16:08
-
\$\begingroup\$ This question seems to be more fitting for a programming se. \$\endgroup\$– angarg12Commented Aug 8, 2014 at 16:15
-
\$\begingroup\$ Note it currently asks a question that seems focussed on a different type of random generation (a multiple decision system) which is again quite different from this one. \$\endgroup\$– ThijserCommented Aug 8, 2014 at 20:25
Add a comment
|
1 Answer
\$\begingroup\$
\$\endgroup\$
2
One way to do this is, take a pseudo random generator and let it generate a float between 0 and 1. You would then multiply it with 100 to get into the range of 0 to 100. If this final value is smaller than the percent of the chance, in this example, the tank would hit the target. Here is some pseudo code, what it could look like:
// chance of tank, hitting the target
float chance = 70.0f;
// first, generate a pseudo random float in the range of 0 to 1
float n = random();
// multiply n with 100 to get into the range of 0 to 100
n = n * 100;
// if n is below chance, the tank will hit the target
if(n < chance)
{
// do something here
}
Edit: Changed from int to float, due to the fact that Anko mentioned.
-
4\$\begingroup\$ The modulo operator is often a really bad idea with random numbers. The maximum integer produced by
random
is in most cases not a multiple of 100, causing a biased output: Imagine if the maximum integer was 150. Everything from 0-100 would% 100
to the range 0-100. Everything from 101 to 150 would mod to 1-50. That means outputs 0-50 are much more likely! Instead, have your RNG generate a float and doif (randomFloat() * 100 < chance) { ... }
. \$\endgroup\$– AnkoCommented Aug 8, 2014 at 16:26 -
\$\begingroup\$ Ok, I didn't thought about that. I will edit my answer. \$\endgroup\$ Commented Aug 8, 2014 at 17:22