It's important that you understand the previous two types of node movement before diving into this one. This one builds upon the previous type of movement. In the previous movement we had Pacman move around from node to node smoothly. However, he always stops on each node. We also can't change his direction when he is traveling between two nodes. In this section we'll change his movement so that he'll only stop on a node if he can't continue on to another node in the direction he is moving, otherwise he'll move past the node. We'll also change it so that he can reverse direction at any time. Once we're done with this section we'll have the completed movement for Pacman. What's really nice is that no matter what maze layout we use, this code will always stay the same.
We're going to create a new method called reverseDirection inside the Pacman class which will allow Pacman to reverse direction at any time. We first change his direction to be opposite to the direction he was moving in. That's why I chose to use opposite values for the direction keys. UP is 1 and DOWN is -1. Likewise, LEFT is 2 and RIGHT is -2. No matter which direction I'm in all I have to do is multiply it by -1 to get the opposite direction. Nice!
Once I get the opposite direction I still have to swap the node and target.
The other method called oppositeDirection just checks to see if the input direction is the opposite of Pacman's current direction. The reason I want to check for this is because when Pacman is moving between nodes, the only direction he can move in is his current direction and his opposite direction. So I want to make sure that the input direction is a valid direction before saying he can move in that direction.
In the update method, if the input direction does not get us a new valid target, then we check the current direction Pacman is moving in. The input direction takes precedence so that's why it is first. If our current direction results in a valid target, then we just continue moving in that direction. If it still doesn't provide us with a valid target, then we stop on the node.
Also, while we're not overshooting a node, which means we're in the process of moving from one node to the other, we can reverse direction.
Once all of these changes are made, test out the code again and you'll see the improved movement. This is how Pacman moves through the maze. The ghosts move through the maze in a similar fashion, but we'll get to that later.