I’m trying to make an NPC with multiple attack patterns that come out randomly based on rng.
However, I want the NPC to use some of the basic attacks more than a stronger one and using math.random
just means all of the attacks have the same chance of happening. I know how to code the NPC but I can’t figure out how I can implement a percent chance into the decision-making function
Math.random() returns a number from 0 to 1. This means it’s actually returning a percentage. So you can simply pick one and stack the chances on top of each other.
For example
local attacks = {
["Attack1"] = 0.56,
["Attack2"] = 0.23,
["Attack3"] = 0.1
}
local pickAttack()
local r = math.random()
for name, percentage in pairs(attacks) do
r -= percentage
if r <= 0 then
return name
end
end
end
This assumes the numbers add to 1. Some small changes can do this without that though.
1 Like
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.