Step 11 of 12
Make the arrow follow the mouse
Add the rest of the update method, at the bottom of it, so Bob works out where to look
to_mouse = pygame.Vector2(mouse_pos) - self.pos
if to_mouse.length_squared() > 0:
self.facing = to_mouse.normalize()
Subtracting Bob's position from the mouse position gives an arrow that goes from Bob to the mouse. We squash it to length 1 with normalize() and store it as facing. The if stops us trying to squash an arrow of length 0, which happens if the mouse is exactly on Bob's centre.
Now draw the arrow. Add this to the bottom of the draw method
# Arrow: line from the head edge plus a triangle tip.
start = self.pos + self.facing * (BOB_RADIUS * 0.5)
tip = self.pos + self.facing * (BOB_RADIUS + 18)
base = tip - self.facing * 10
side = pygame.Vector2(-self.facing.y, self.facing.x) * 6
pygame.draw.line(surface, ARROW_COLOR, start, base, 3)
pygame.draw.polygon(surface, ARROW_COLOR, [tip, base + side, base - side])
It's built from three points along the line Bob is facing:
startis a bit inside Bob's head.tipis the sharp point, 18 pixels past the edge of his head.baseis 10 pixels back from the tip, where the triangle begins.sideis a small arrow pointing sideways to the facing direction. Swapping the two numbers and flipping one sign turns an arrow by a quarter turn, which is a neat trick. We use it to find the two corners of the triangle either side ofbase.draw.linedraws the shaft (3 pixels thick) anddraw.polygonfills in the triangle from the three corners: the tip, and the two sides.
Run it and wiggle the mouse around. The arrow should spin to follow it while you walk around with the keyboard.