Need feedback on hit chance calculation
Asked Answered
C

3

0

This is more of a math question. I want to understand how percentage calculation works, for something like crit chance, hit chance or item drops.

Is this code here roughly correct? Any feedback on how to do it better/smarter/more in depth? I'm pretty terrible at math, so any "probability calculation for idiots", especially on how to do it in Godot specifically, is greatly appreciated.

var hit_chance = 0.60 # hit chanc would be 60%
var evasion_boost = 0.2 # evasion chance would be 20%
var hit = false

func _ready():
	calculate_hit()

func calculate_hit():
	for i in 5:
		var evasion = randf()
		evasion += evasion_boost # add evasion boost to evasion
		if evasion <= hit_chance:
			hit = true
		else: hit = false

EDIT: on second glance, i'm not sure what i was trying to accomplish with that code above. Here's better code. I think?

var hit_chance = 0.90 # hit chance is 90%
var evasion_boost = 0.2 # evasion chance is 20%
var hit = false

func _ready():
	calculate_hit()


func calculate_hit():
	var chance = hit_chance - evasion_boost # subtract evasion from hit chance
	var percentage = chance * 100
	print("hit chance is ", str(percentage), "%")
	var RNG = randf()
	print("RNG is ", RNG)
	if RNG >= chance:
		print("you hit!")
	else: print("you missed!")
Caught answered 23/2, 2024 at 19:51 Comment(0)
S
0

Caught the second one looks on the right path but you're missing a piece. Just make sure to use randomize() before or else you won't get truly random seeds.... translation: the randomization won't be random in randf(). So, to edit the code:

var hit_chance : float = 0.90 # hit chance is 90%
var evasion_boost : float = 0.2 # evasion chance is 20%
var hit : bool = false

func _ready():
	calculate_hit()


func calculate_hit():
	var chance = hit_chance - evasion_boost # subtract evasion from hit chance
	var percentage = chance * 100
	print("hit chance is ", str(percentage), "%")
        randomize()
	var RNG = randf()
	print("RNG is ", RNG)
	if RNG >= chance:
		print("you hit!")
	else: print("you missed!")
Struck answered 23/2, 2024 at 21:0 Comment(0)
C
0

Struck Calling randomize() randomizes the seed, yes? That's useful for sure, though my question is more towards the logic of my code itself.

After sleeping over it, i believe i messed up the part about comparing whether the RNG value is higher or lower. It should be

if RNG <= chance

And not > than chance.

Admittedly decimals are always short-circuiting my brain, so i tried imagining it more like a number between 1 to 100. If your chance to hit is 70%, then the number should roll between 1-70 for a hit. If it rolls a 71 or higher, it's a miss. Can some confirm that logic for me? My brain feels like spaghetti at this point.

Caught answered 24/2, 2024 at 7:22 Comment(0)
S
0

Caught haha i get that. no you're spot on with the math. 👍️

Struck answered 24/2, 2024 at 17:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.