/** * //this was loosely adapted from a reddit post that I basically just used their general idea of * //1. Find the direction from evil avatar to avatar * //2. Convert this direction into a unit vector * //3. Move the avatar * Source: https://www.reddit.com/r/libgdx/comments/pm6545/how_to_make_an_enemy_follow_the_player/ * //I also added some random movements from the evil avatar so that they don't * end up chasing the avatar too hard so that the user immediately loses and they rage quit :( */ // public void moveEvilAvatarTowardsPlayer() { int newX = evilX + Integer.compare(avatarX - evilX, 0); int newY = evilY + Integer.compare(avatarY - evilY, 0); if (newX == lastEvilX && newY == lastEvilY) { moveRandomly(); //make sure that it will just randomly move if they choose to stay in the same position } else if (canMoveTo(newX, newY)) { moveEvilAvatar(newX, newY); } else { moveRandomly(); //when in doubt just let this thing move randomly } lastEvilX = evilX; lastEvilY = evilY; } private void moveRandomly() { List<Point> possibleMoves = new ArrayList<>(); for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) continue; int canx = evilX + dx; int cany = evilY + dy; if (canMoveTo(canx, cany)) { possibleMoves.add(new Point(canx, cany)); } } } if (!possibleMoves.isEmpty()) { Point randomMove = possibleMoves.get(random.nextInt(possibleMoves.size())); moveEvilAvatar(randomMove.x, randomMove.y); } } private boolean canMoveTo(int x, int y) { return x >= 0 && x < width && y >= 0 && y < height && tiles[x][y] == Tileset.FLOOR; } private void moveEvilAvatar(int newX, int newY) { tiles[evilX][evilY] = Tileset.FLOOR; evilX = newX; evilY = newY; tiles[evilX][evilY] = Tileset.EVIL; } //in main //sets menu and HUD if (currentState == GameState.MENU) { handleMenuChoice(currentKey); needsRender = true; } else if (currentState == GameState.GAME_RUNNING) { gameWorld.moveAvatar(currentKey); gameWorld.moveEvilAvatarTowardsPlayer(); needsRender = true; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter