Unaccurate distance between gameObjects

Hey guys, I’ve tried searching on the forums for this but I can’t find a suitable solution.

I’m trying to build a puzzle game that depends on accurate distance between GameObjects. This is not a classic puzzle, although things are aligned like in a grid, items can drop from altitudes, bounce, get launched … etc. And they most always be alinged.

I use raycasts to check for objects beside the puzzle item the user interacts with, and it all works fine. But I would like to have an accurate distance between gameobjects to know when an objects is exactly beside, or maybe on the next column in the imaginary grid. So if there is an exact distance of 0.25f between all items that are beside each other, if the distance is 0.50f I know there would be an empty space in between, and so on…

So far I have solved this by adding a small margin like 0.01f when I check the distance, and the game works fine like this. But I woud like to know if there is a better way to deal with this issue.

Many Thanks.

Due to floating point inaccuracies there isn’t any better way. You can try something like:

if (Mathf.Abs(x2-x1)>0.49) to check if they’re apart by 0.5, but I’m sure you know that. This is normal behaviour for floats.

For a puzzle game it is better to work with grid “cells” in integer coordinates then merely multiply up or down to fit on screen.

Thanks hippocoder.

Just to confirm… the inaccuracies are always under the original number, right? What I mean is that if I have an exact distance of .25f in the editor, when I check at runtime the distance is always going to be something like… 0.24654321 or 0.249873524… but never 0.2554635. So its never OVER the original number, correct?

Then that rule of rounding up before checking is never going to fail, in theory of course.

The method Hippocoder provided works regardless of whether the number is greater or less than the approximation. It compares the absolute values (that’s what the Mathf.Abs call is for) so if the difference is negative, it will be converted to positive for the comparison.

Ok thanks guys it works good so far like this. :slight_smile: