Hello,

I've got some code for a 2d game that orients an NPCs graphic towards the direction he is walking to. There are 4 directions (down, left, right, up), that have the values (0, 1, 2, 3) respectively (so 3 - direction will yield the other direction on that axis). It is possible for the NPC to walk straight, diagonally, and unevenly-diagonally (2 pixel on the x-axis, 1 on the y-axis, hope you know what I'm talking about). Now the code for mapping this movement to the direction is rather clumsy, just a big mess of if-statements:

unsigned int DirectionFromMove(const math::Vector2& vMove) { if(vDir.x > 0) { if(vDir.y > 0) { if(vDir.x > vDir.y) return 2; else return 0; } else if(vDir.y < 0) { if(vDir.x > abs(vDir.y)) return 2; else return 3; } else return 2; } else if(vDir.x < 0) { if(vDir.y > 0) { if(abs(vDir.x) > vDir.y) return 1; else return 0; } else if(vDir.y < 0) { if(vDir.x < vDir.y) return 1; else return 3; } else return 1; } else { if(vDir.y > 0) return 3; else if(vDir.y < 0) return 0; } }

I thought about it for a while, but didn't find any better way myself. I'm really curious, since in "production"-code I always end up with stuff like this. Is there some clever solution here to get rid of all the ifs?