hello,
So Im making a kinda rpg-topdown-engine-game-thing and I want to have the function for the player to collide with other players. so it looks like this:
But here is the problem!
You see, the player checks if the tile he is about to go to is a wall or another player, if so he goes back (doesn't move). seems ok, right?
NO
players are stored in a big table players={} and the checking process is done in a foreach loop. So when the player below moves up, he sees that there is someone above, he doesn't move, but the upper one moves. Its hard to explain look:
did you see it? when I pressed down only the bottom player moved. Because the upper one (index 1) checks first and sees that there is a player below him, no move. then the bottom one checks and moves.
How can I fix this?
If you have any questions for the code or the game feel free to ask.
Thanks for taking your time to read this :)
Will they always move in the same direction, or could you end up with something like:
1 | 2- |
where 1 is moving down and 2 is moving right and they end up in the same spot?
When you press a direction key, add that direction intention yo each player object. Loop over every player, and if possible , move the player and remove its intention flag.
If a player has moved, restart the player scan from the start.
Once you have reached the end of the list, it means that everyone that could move did. Do a last sweep to remove the remaining intention flags of stuck players
Iterate over the units by their position along the direction you're trying to move. For example if you move up start from the lowest to highest y position, for right start from highest to lowest x position. I'd build an ordered list of units to update each time a direction is pressed and just iterate over that with your existing logic, which should work fine now as any unit which may end up blocking another will finish its move first. It requires a sort on each move but with a smallish number of units to move it won't be a problem and saves doing multiple passes to get the correct result.
thanks alot for all the responses, I think I found the solution. Two foreach loops, first one containing all code stuff, second one only checks if the players are colliding. So all players are moved, no matter what (except walls), then again In a loop they see if they are overlapping and if so the overlapping one moves back. thanks again :)
@cheesemug, that would work, but only if every player is interchangeable without consequence. If not, say players can have different Colors for example, then the two suggested solutions (intention flag and player sorting by coordinates) would work.
[Please log in to post a comment]