Game Development Reference
In-Depth Information
controllers are built. Remember the two-axis controller I mentioned earlier? X and Y
are both analog electrical devices called potentiometers. They measure electrical resis-
tance along an analog dial and are used for things like volume controls on stereos
and, of course, joysticks and thumbsticks. On two-axis controllers like these, you
have two potentiometers: one for each axis.
You can see from Figure 9.3 that the Y potentiometer can reach 1.0 or
1.0 if you
push the controller all the way up or down. You can get the same values for the X
potentiometer. You might think that all you need to do to calculate the input speed is
find the length of the combined vector. That ' s just classic geometry, the Pythagorean
Theorem.
a 2 þ b 2 ¼ c 2
a 2 þ b 2
p
¼ c
p
1 2
¼
p ¼ 1 : 414
þ 1 2
This length is represented by the gray arrow in Figure 9.3. The problem is that the
new input vector is 1.414f units long, and if you feed it right into the game, you ' ll be
able to move diagonally quite a bit faster than in the cardinal directions. The direc-
tion of the new vector is correct, but it is too long.
For character movement, the forward/back motion of the character is mapped to the
up/down movement of the thumbstick, and the left/right motion of the character is
mapped to the left/right movement of the thumbstick. Usually, the speed of the char-
acter is controlled by how far the thumbstick is pushed. If you push the thumbstick
all the way forward, the character will run forward as fast as it can.
But look at what happens when you want the character to run and turn left at the
same time, as Figure 9.3 would suggest. Since I have to move the controller to the
left, I automatically increase the length of the X input while the Y value stays at
1.0f, and the character begins to run too fast.
The solution to this problem is actually pretty simple: The speed of the character is
mapped to the length of the X/Y 2D vector, not the value of the Y control alone, and
you have to cap the speed at 1.0f. All you do is take the capped length and multiply it
by the maximum speed:
int speed = maxSpeed * min(1.0f, sqrt((x * x) + (y * y)));
Of course, you may have different maximum speeds for going forward and backward,
or even side to side.
You might not realize it, but you also want to use this normalizing scheme on key-
board input. Consider the classic WASD scheme used by most first-person shooters
on the PC. W and S move the player forward and back. A and D strafe the player
Search WWH ::




Custom Search