Back

Input + Physics

Reading

It should be possible to explain the laws of physics to a barmaid. [Albert Einstein]

PVectors

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!

Declaring and Initializing PVectors

Basic Physics Movement

We've seen parts of this before. xPos += xVel. Here is the final physics update method for our characters and objects.

A Move Method

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.

Theory

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.

When using the set method of a PVector, you must use 3 arguments
Use PVectors instead of seperate variables for things like coordinates (x, y, z)

Keyboard Input

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.

When referring to keys, remember they are char data types and you must use single quotes.
The keyPressed and keyReleased methods are only called once when a key is pressed, or released

Holding Multiple Keys

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.

Using Stored Key States