I am making a game on a WP7 device using C# and XNA. I have a system where I always want the object the user is touching to be brought to the top, so every time it is touched I add float.Epsilon to its draw depth (I have it set so that 0 is the back and 1 is the front).
On the Emulator that all works fine, but when I run it on my device the draw depths seem to be completely random.
I am hoping that anybody knows a way to fix this. I have tried doing a Clean & Rebuild and uninstalling from the device but that is no luck. My call to spritebatch.Begin is:
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
and to draw I use
spriteBatch.Draw(Texture, new Rectangle((int)X, (int)Y, (int)Width, (int)Height), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, mDrawDepth);
Where mDrawDepth is a float value of the draw depth (likely to be a very small number; a small multiple of float.Epsilon.
Any help much appreciated, thanks!
The problem is your use of
float.Epsilon. From the documentation:I expect that the emulator is not running a completely accurate emulation of ARM – which is why it works correctly on the emulator and not the device. (I’m not even sure the emulator is actually running ARM – it may well be x86.)
It should be noted that adding epsilon to things and expecting the resulting value to be meaningful is highly risky. The value of
float.Epsilonis the precision of 32-bit floating point numbers (on x86) around zero.At numbers of greater magnitude than zero, the precision delta becomes larger. There will come a point where adding
float.Epsilonto a given value will give you exactly that value back.Without getting into a detailed description of how floating-point works, I will just point out that a 32-bit float (when considered in base-10) can store 6 (or so) significant digits.
Personally I would recommend implementing your own ordering system. I’ve always found the
layerDepthstuff in XNA kind of weak.Perhaps you’re drawing these components from a list? Just re-order the list when a component is touched?