← All stepsBobgame: make a Python game

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:

Run it and wiggle the mouse around. The arrow should spin to follow it while you walk around with the keyboard.