Created
November 18, 2012 22:55
-
-
Save pyrobot/4107968 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public bool Nearby(Point enemyLoc, Point playerLoc, int distance, Direction direction) | |
{ | |
//it helps human understanding and debugging to do all your calculations seperately, instead of one massive hard to read switch/if statements | |
bool isNearby = false; | |
//get the deltas | |
int deltaX = playerLoc.X - enemyLoc.X, | |
deltaY = playerLoc.Y - enemyLoc.Y; | |
//determine direction, you may need to flip which one is negative and positive for it to work | |
int xDir = 0, yDir = 0; | |
if (deltaX > 0) { | |
xDir = 1; | |
} else (deltaX < 0) { | |
xDir = -1; | |
} | |
if (deltaY > 0) { | |
yDir = 1; | |
} else (deltaY < 0) { | |
yDir = -1; | |
} | |
//get actual distance | |
int distX = Math.Abs(deltaX), | |
distY = Math.Abs(deltaY); | |
switch (direction) | |
{ | |
//now the switch statement is alot cleaner, and easier to read for a human | |
case Direction.Up: | |
if (distY < distance && xDir == 0 && yDir > 0) | |
isNearby = true; | |
break; | |
case Direction.Down: | |
if (distY < distance && xDir == 0 && yDir < 0) | |
isNearby = true; | |
break; | |
case Direction.Left: | |
if (distX < distance && yDir == 0 && xDir > 0) | |
isNearby = true; | |
break; | |
case Direction.Right: | |
if (distX < distance && yDir == 0 && xDir < 0) | |
isNearby = true; | |
break; | |
} | |
return isNearby; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment