How to make a sprite follow your mouse cursor using pygame?

10,216

There is a line-by-line Chimp game tutorial that shows you how to do this. Check out the Fist class and in particular, the update method:

class Fist(pygame.sprite.Sprite):
    """moves a clenched fist on the screen, following the mouse"""

    def update(self):
        "move the fist based on the mouse position"
        pos = pygame.mouse.get_pos()
        self.rect.midtop = pos
        if self.punching:
            self.rect.move_ip(5, 10)

To play the game:

In [112]: import pygame.examples.chimp

In [113]: pygame.examples.chimp.main()

The code for the game is packaged with pygame. To find out where the code is located using IPython:

In [114]: pygame.examples.chimp.main?
Type:       function
String Form:<function main at 0xb14dae4>
File:       /usr/lib/python2.7/dist-packages/pygame/examples/chimp.py

Or to find where the code is located using the Python interpreter:

>>> import inspect

>>> inspect.getabsfile(pygame.examples.chimp.main)
Out[116]: '/usr/lib/python2.7/dist-packages/pygame/examples/chimp.py'
Share:
10,216
Ark Angel
Author by

Ark Angel

i'm fairly new to programming with basic knowledge in Python, Robot C, html/css. I'm not very good so i do ask alot of questions :(

Updated on June 27, 2022

Comments

  • Ark Angel
    Ark Angel almost 2 years

    I am making a small game for a class project and am wondering how to make something follow my mouse cursor using pygame. I'm new to pygame so try to be understanding if it's obvious and I'm just stupid.