-1

I have a simple function that returns bool value as a result of comparison of distance between 2 entities to GravityRadius field.

public bool IsEntityPulledByGravity(IEntity entity)
{
    return Vector3.Distance(State.Position, entity.State.Position) <= GravityRadius;
}

Sometimes it works as it suppose to but sometimes it returns incorrect false value. I entered debug mode to analyse it and I can't figure out why it would return false for comparison of 30 <= 30. What am I missing?

enter image description here

FullStackForger
  • 1,060
  • 2
  • 12
  • 18

2 Answers2

5

You shouldn't compare floating point numbers for equality.

This MSDN article specifically describes the situation for System.Single. System.Single.Equals under the section Precision in Comparisons.

Paul Mitchell
  • 3,241
  • 1
  • 19
  • 22
1

make sure whatever you are comparing are of the same datatype, you can cast them to same datatype before comparing . Use compareTo in your case since Single class implelements the IComparable interface check this link https://msdn.microsoft.com/en-us/library/system.single(v=vs.110).aspx

Emmanuel Ogoma
  • 584
  • 5
  • 12