Shorter turning code using vector math

This commit is contained in:
Matt Low 2019-12-28 12:48:20 +04:00
parent 8a0298b2db
commit f6fbad0e6d
2 changed files with 19 additions and 43 deletions

View File

@ -30,6 +30,10 @@ public abstract class Entity {
return (int) pos.x == (int) other.pos.x && (int) pos.y == (int) other.pos.y;
}
public Vector2 getTileVector(float offset) {
return new Vector2((int) pos.x + offset, (int) pos.y + offset);
}
public Vector2 getTileVector() {
return new Vector2((int) pos.x, (int) pos.y);
}

View File

@ -43,51 +43,23 @@ public abstract class MovableEntity extends Entity {
if (nextDirection != null) {
boolean turned = false;
switch (nextDirection) {
case UP:
nextTile = state.level.getTile(pos.x, pos.y + 1f);
nextTile = state.level.getTile(nextDirection.getVector().add(pos));
if (nextTile == null) {
if (currDirection == Direction.DOWN) {
// turned around immediately after existing tunnel (or trying to turn 90 degrees after entering tunnel)
if (nextDirection.isOpposite(currDirection)) {
// only allow if turning 180 degrees
turned = true;
}
} else if (nextTile.isPassable() && Math.abs(pos.x - ((int) pos.x + 0.5f)) <= tolerance) {
pos.x = ((int) pos.x) + 0.5f;
} else {
if (nextTile.isPassable()) {
// it's possible to turn - are we close enough to our tile's center to make the turn?
Vector2 tileCenter = getTileVector(0.5f);
if (pos.dst2(tileCenter) <= tolerance * tolerance) {
// yes, move us to the center of our tile
pos = tileCenter;
turned = true;
}
break;
case RIGHT:
nextTile = state.level.getTile(pos.x + 1f, pos.y);
if (nextTile == null) {
if (currDirection == Direction.LEFT) {
turned = true;
}
} else if (nextTile.isPassable() && Math.abs(pos.y - ((int) pos.y + 0.5f)) <= tolerance) {
pos.y = ((int) pos.y) + 0.5f;
turned = true;
}
break;
case DOWN:
nextTile = state.level.getTile(pos.x, pos.y - 1f);
if (nextTile == null) {
if (currDirection == Direction.UP) {
turned = true;
}
} else if (nextTile.isPassable() && Math.abs(pos.x - ((int) pos.x + 0.5f)) <= tolerance) {
pos.x = ((int) pos.x) + 0.5f;
turned = true;
}
break;
case LEFT:
nextTile = state.level.getTile(pos.x - 1f, pos.y);
if (nextTile == null) {
if (currDirection == Direction.RIGHT) {
turned = true;
}
} else if (nextTile.isPassable() && Math.abs(pos.y - ((int) pos.y + 0.5f)) <= tolerance) {
pos.y = ((int) pos.y) + 0.5f;
turned = true;
}
break;
}
if (turned) {
currDirection = nextDirection;