Step 10 of 12
Move Bob with W A S D
Add this update method to the Bob class in player.py, between __init__ and draw
def update(self, dt: float, keys, mouse_pos) -> None:
direction = pygame.Vector2(
keys[pygame.K_d] - keys[pygame.K_a],
keys[pygame.K_s] - keys[pygame.K_w],
)
if direction.length_squared() > 0:
direction.normalize_ip()
self.pos += direction * BOB_SPEED * dt
self.pos.x = max(BOB_RADIUS, min(WIDTH - BOB_RADIUS, self.pos.x))
self.pos.y = max(BOB_RADIUS, min(HEIGHT - BOB_RADIUS, self.pos.y))
keys is a list of every key on the keyboard, and each one is True if it's being held down or False if not. Python treats True as 1 and False as 0, so we can do maths with them.
- Across:
DminusA. If you holdDthat is1 - 0 = 1(right). HoldAand it's0 - 1 = -1(left). Hold both and they cancel out to0. - Down:
SminusW, the same trick.Wis-1because up is negative. - So
directionends up as a little arrow telling us which way you want to go. HoldDandStogether and it's(1, 1), down and to the right. - There's a catch.
(1, 1)is a longer arrow than(1, 0), so going diagonally would be faster than going straight. That's a sneaky bug lots of games have.normalize_ip()fixes it by squashing any arrow to a length of exactly 1, while keeping the direction. We only do thatifthe arrow isn't zero length, because you can't squash nothing. self.pos += direction * BOB_SPEED * dtis the actual move. Direction (which way) times speed (250 pixels per second) timesdt(how many seconds this frame took). If a frame takes 1/60 of a second, Bob moves about 4 pixels. Usingdtmeans he moves at the same speed on a fast computer or a slow one.- The last two lines are a fence.
minpicks the smaller of two numbers andmaxpicks the bigger, so together they trapxandybetween the edges of the window. We leave a gap ofBOB_RADIUSso the whole head stays in view.
The mouse_pos isn't used yet, we'll use it in the next step. In game.py we need to call update on every frame. Add this to step, right before the line that paints the background
self.bob.update(dt, pygame.key.get_pressed(), pygame.mouse.get_pos())
pygame.key.get_pressed() hands over the list of keys and pygame.mouse.get_pos() gives the mouse position. Run the game and use W A S D. Bob should glide around and stop at the edges.