- Home /
Damage calculation seems off when dealing with decimals
Hello community
I'm having troubling finding out why my calculations seems off, when receiving damage, and the damage being 0.2. As you can see on the picture below, at some point my HP will have an insane decimal number.
My damage calculation is a basic: health -= damage; where both variables are floats.
From test it seems after the 5th hit, I will end up with x.000001 I'm rather new to Unity, but is that just how floats works ?
I tried to resort to double, but I use Vectors in some calculations in terms of knockback and healthbar, so I don't think it would be wise of me to redo all my floats to doubles, as then I would have to find another way to convert Vector3 to doubles, which I don't know is possible rn.
I tried to do on my take damage formulas the following, but didn't yield any changes:
public void TakeDamage(float damage, Vector3 playerpos)
{
health = (health * 100f) / 100F;
damage = (damage * 100f) / 100f;
health -= damage;
// knock back
Vector2 knockbackPosition = (transform.position - playerpos).normalized * knockbackForce;
GetComponent<Rigidbody2D>().velocity = knockbackPosition;
}
Kind regards DaPham
Answer by LCStark · Sep 23, 2018 at 01:00 PM
You're right, it is just how floats work. Can't you work on ints instead? You could keep your health and damage values as integers with 10 times bigger value (in your example, 22 health points and 2 points of damage) and only convert them to floats when you need to display them to the player.
Arh that makes sense.
I could, I'm just working around how if it would bug the game at a later stage with equipment/stats as multipliers, but I guess I can always round up/down with $$anonymous$$ath.Floor.
Thanks for the fast reply!
Your answer
Follow this Question
Related Questions
Object Not Recieving Damage 3 Answers
Expecting ) found = 1 Answer
Enemy Health Damage 2 Answers
2D GUI Group moving with players. 1 Answer
Addjustcurrenthealth not working 0 Answers