I assume your values are
int
.
There is a function called
Math.Abs(...)
.
[EDIT]
Your function is broken. Coordinates may be in general positive as well as negative (a point may lay in any of the four
quadrants[
^]). If you take the absolute value of the coordinates
before you calculate the coodinate distance results in wrong results. Take the values as they are.
public int GetDistanceFromEntity(Entity Entity)
{
int deltaX = Entity.PositionX-PositionX;
int deltaY = Entity.PositionY-PositionY;
return (int)Math.Sqrt(deltaX*deltaX + deltaY*deltaY);
}
You can test it with points in all quadrants and in both directions:
var q1=new Entity(1, 2);
var q2=new Entity(-3, 2);
var q3=new Entity(-3, -1);
var q4=new Entity(4, -1);
var p0=new Entity(0, 0);
Assert.AreEqual(0, q1.GetDistanceFromEntity(q1), "identiy should have distance 0");
Assert.AreEqual(0, q2.GetDistanceFromEntity(q2), "identiy should have distance 0");
Assert.AreEqual(0, q3.GetDistanceFromEntity(q3), "identiy should have distance 0");
Assert.AreEqual(0, q4.GetDistanceFromEntity(q4), "identiy should have distance 0");
Assert.AreEqual(0, p0.GetDistanceFromEntity(p0), "identiy should have distance 0");
Assert.AreEqual(q2.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(q2), "distance should be invariant");
Assert.AreEqual(q3.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(q3), "distance should be invariant");
Assert.AreEqual(q4.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(q4), "distance should be invariant");
Assert.AreEqual(p0.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(p0), "distance should be invariant");
Assert.AreEqual(4, q1.GetDistanceFromEntity(q2), "distance q1-q2 mismatch");
Assert.AreEqual(5, q1.GetDistanceFromEntity(q3), "distance q1-q3 mismatch");
...
[/EDIT]
Cheers
Andi