As part of my 2 player top-down survival combat game, I want the zombies to detect the nearest player and head for them. Here is the code I use:
I know it's a bit messy, but I thought it would still do the job. However, it doesn't work properly. sometimes, the zombie will go for one player even though they are not the closest, other times it will walk to one player, then walk to the other, then back to the first etc. Does anyone know how to fix this?
Board board = (Board)getWorld(); int playerBluePos = board.playerBlueX + board.playerBlueY; int playerRedPos = board.playerRedX + board.playerRedY; int zombiePos = getX() + getY(); if (playerBluePos - zombiePos < 0 && playerRedPos - zombiePos > 0 || playerRedPos - zombiePos < 0 && playerBluePos - zombiePos > 0) { playerRedPos = -playerRedPos; } if (playerRedPos < 0) { if (playerRedPos > playerBluePos) { turnTowards(board.playerRedX, board.playerRedY); move(speed); walkProgress += speed; } else { turnTowards(board.playerBlueX, board.playerBlueY); move(speed); walkProgress += speed; } } if (playerRedPos > 0) { if (playerRedPos < playerBluePos) { turnTowards(board.playerRedX, board.playerRedY); move(speed); walkProgress += speed; } else { turnTowards(board.playerBlueX, board.playerBlueY); move(speed); walkProgress += speed; } }