Here's the script reference document for Mathf.FloorToInt As you can see, it should round -0.5 down to -1. For some reason it seems to return it as 0 when used with my calculations.
I have two versions of the same functions that work in a very similar way but give different outputs. My code will only ever submit integers between 3 and 18 to these functions.
This version acts as if it were using Mathf.CielToInt (returns 0 in a case of statRoll = 9):
public int getBonus(int statRoll)
{
int result = Mathf.FloorToInt((statRoll - 10) / 2);
return result;
}
This is the version that works (returns -1 in a case of statRoll = 9):
public int getBonus(int statRoll)
{
float initial = statRoll - 10;
float divided = initial / 2;
int result = Mathf.FloorToInt(divided);
return result;
}
You are getting bit by integer division. Both statRoll
and 10
are int
type, that makes initial
actually a int
.
Your first code is equivalent to
public int getBonus(int statRoll)
{
int initial = statRoll - 10;
int devisor = 2;
int divided = initial / devisor;
float castDevided = (float)divided
int result = Mathf.FloorToInt(castDevided);
return result;
}
When you do -1 / 2
you have two ints, this evaluates to 0
not -0.5
because the result must also be a int. The way to fix this is make one of the two values a float
public int getBonus(int statRoll)
{
int result = Mathf.FloorToInt((statRoll - 10) / 2f); //adding f after a number makes it a float
return result;
}
This makes the division between a int
and a float
which results in a float. The similar code would be
public int getBonus(int statRoll)
{
int initial = statRoll - 10;
float devisor = 2f;
float divided = initial / devisor ;
int result = Mathf.FloorToInt(divided);
return result;
}