XNA Custom Sprite Sorting on Z Plane

Started by
1 comment, last by lodoss118 12 years, 6 months ago
Hi guys i am kinda confused, i have a list of entities which i sort on the z plane (mimic games like final fight depth) i have a IComparer function like this

class CEntityComparer : IComparer<CEntity>
{
public int Compare(CEntity e1, CEntity e2)
{
float z1 = e1.GetZ();
float z2 = e2.GetZ();
return z1.CompareTo(z2);
}
}

but i seem to get zome z fighting problems when they are probably on the same z plane?

and i can't do something like this?

class CEntityComparer : IComparer<CEntity>
{
public int Compare(CEntity e1, CEntity e2)
{
float z1 = e1.GetZ();
float z2 = e2.GetZ() + 5;
return z1.CompareTo(z2);
}
}

i keep getting a nullpointer exception saying that Comparer is inconsistent?
Advertisement
Never seen that error before, but it sounds like the method is screwing up because your objects are not returning a consistent sort value, which means they can't be sorted.

See: A = 1 and B = 2.
But when Compare(A, B) gets run, A = 1, and B = 7. If another object gets compared, it will look like Compare(B, C).. but this time B = 2, and C = 8.
But B can't equal 2 *AND* 7. So the sort fails and an exception is raised.

The way the compare function is called, you can never be sure which elements get passed in in any particular order.. that's dependent on the sort algorithm. All you're modifying is how the objects compare to each other.

The easiest way would be to sort at the end by something unique to the entity. For instance, if you already have an Entity.ID, just sort by that.



public int Compare(Entity e1, Entity e2)
{
float z1 = e1.GetZ();
float z2 = e2.GetZ();
if (z1.Equals(z2))
if (e1.ID.Equals(e2.ID))
return 0;
else return e1.ID.CompareTo(e2.ID);
else return z1.CompareTo(z2);
}

Note: Return 0 means the objects are identical.. since you're already using the CompareTo function, you probably know that. The "return 0" should never get hit during the sort, because the same entity.ID should never exist twice in your entity list. But it's best to leave it in there, because you can use the Compare function in other ways.

In this way, a lower ID will always be ordered first, then a higher ID. This will give you the consistency you need for overlapping objects.The flickering is caused because two objects COMPARE equally to each other. In the first sort, entity1 may end up before entity2... but in the second sort, because they're equal, there's a chance that entity2 ends up before entity1. Doing this 60 times a second means the objects change places very rapidly, producing a noticeable flicker.
thanks mate seems to be working fine now :)

This topic is closed to new replies.

Advertisement