It should be possible to explain the laws of physics to a barmaid. [Albert Einstein]
Processing includes a special type called a PVector which is simply an object that has fields x, y, z, and some special methods to perform vector math calculations, making them very convenient for physics!
We've seen parts of this before. xPos += xVel. Here is the final physics update method for our characters and objects.
Now that our update method is perfected, we only need a simple move method with a single parameter to apply a small force to our acceleration PVector.
What will happen when the move method is called as a result of a keypress? The acceleration vector will have the move force applied to it, changing it's x,y,z values. The next time we call our update method, these values are applied to the velocity. The velocity must then be "dampened" to ensure our object never gets too fast. Velocity is added to the position, and finally we must clear all the forces from the acceleration PVector by setting all fields to 0 using the set method.
There are two methods for working with the keyboard: keyPressed() and keyReleased()
Here's how you check what key was pressed:
How about special keys, like the arrow keys:
The keyReleased() method works in the exact same way, except it will be called when a key is released.
Since the keyPressed() and keyReleased() methods are only called when the key is pressed or released, in order to maintain the "state" of keys currently "down" we must store this ourselves.