- Home /
C# round transform.position floats to .5
I would like to round my gameobjects transform.position floats to .5 when I move. I was able to get it to work with Mathf.RoundToInt but with Mathf.Round/2 the gameobject never makes it to 0.5 resets back to 0 and then locks up. What am I doing wrong with my code?
Vector3 movePositions = new Vector3(Mathf.Round(transform.position.x + Input.GetAxis("Horizontal"))/2,Mathf.Round(transform.position.y + Input.GetAxis("Vertical"))/2,transform.position.z);
transform.position = Vector3.Lerp(transform.position, movePositions, Time.smoothDeltaTime);
If you're doing this in an Update function it may be that your Input.GetAxis isn't getting a large enough value to step up the transform position high enough before getting rounded off every frame.
Answer by nesis · May 27, 2015 at 11:46 PM
Hi, I think you're wanting Mathf.Round(). It still rounds to the nearest while number, but doesn't return an integer.
To round how you're wanting, I'd make a function like this :
public static float RoundToNearestHalf(float a)
{
return a = Mathf.Round(a * 2f) * 0.5f;
}
Any float you pass into that function will be rounded to the nearest 0.5 :)
Another thing to note, you'll want to at least occasionally check and correct the actual values in transform.position, to ensure they're still rounded to 0.5. Depending how you move that transform, you will get consecutive rounding errors, which can quickly add up and result in inaccurate placement of your object.
If you're dealing with VERY large values, this function might be a safer option:
public static float RoundToNearestHalfSafer(float a)
{
return a = a - (a % 0.5f);
}
This version uses the modulus operator to get the remainder of dividing "a" by 0.5, then subtracts that from "a" to get a rounded value.
Thank you, this quick code helped me do what I need. For completion;
public static float SnapTo(float a, float snap)
{
return $$anonymous$$athf.Round(a / snap) * snap;
}
This doesn't take negative numbers into account.
Answer by triangle4studios · Apr 26, 2021 at 08:11 PM
Or simply:
public static float Half(float value)
{
return Floor(value) + 0.5f;
}
// Standalone Floor Function, Not necessary, but good for beginners to understand how it works.
public static float Floor(float value)
{
return value > 0 ? (value - value % 1) : (value - (value % -1));
}