Grid based movement collision detection

I have a bit of a problem with my movement and I am not sure it is solvable at all…

I have player and enemies moving on a grid and I want them to not move into each other. I can’t use physical colliders, since they then would stop somewhere and not on distinct grid points. I can’t use raycasting, since they all move at the same time, so when there is a empty tile between two objects and they both want to go there, raycasting would allow it. I have tried using an array to set specific tiles invalid when occupied, but that somehow doesn’t work during runtime (probably because I coded it wrongly) and suffers the same problem as raycasting anyway.

Anyone here has an idea, or am I screwed?

Well, you could do it in a two-pass way- every object sets the tile it wants to move to as 'occupied', and then the engine checks for whether any given object is allowed to move, given the one-step-forward occupation status! Just out of interest, if two objects want to move to the same grid location, how does it determine which one gets to go first? I don't quite understand how this works, given that they 'all move at the same time'.

Although they move at the same time, I doubt the engine calculates it at the same time for both objects, so whoever is calculated first, has priority, with the player having priority over all enemies. How would I do this? Store all destinations in an array and then compare each to every subsequent one and recalculate (or stop) the ones that are the same? Wouldn't that take quite some time to calculate?

1 Answer

1

Don’t bother with physics and raycasting and so on, just use a 2D array that represents the game world. Check the array for what it contains, and do collision based on that.

I would highly recommend using a 2D array like I mentioned instead, that way you can directly look up whether a cell is occupied using the grid x/y coords in a single statement, rather than using a for loop.

I tried that earlier, it was the first ting I tried, and multiple times, but it never worked. I had a 2D array that I filled with boolean values and if a tile was occupied I set the corresponding entry to false, but it was extremely slow during runtime and also not very reliable (probably because I did it wrongly).

There's no reason for it to be slow or unreliable, so I'd recommend fixing that code. It would be much faster than using a for loop.

I guess the problem was that two or more objects wanted to write in the same entry at the same time, or some such, but I can try again...

Ok...it is not slow, no idea what I did wrong the other times, but it is still error prone: it happens that tiles become inaccessible permanently, although I set the current location and the next location unoccupied on death.