Search code examples
pythonpygame2d-games

implement mouse motion on pygame


I'm working on a clone of space shooter and I need to use the mouse to move the player, right now the player is moving to the left and right key on pressing the arrow keys.

here's a fragment of my code.

class Player(pygame.sprite.Sprite):
def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    ## scale the player img down
    self.image = pygame.transform.scale(player_img, (50, 38))
    self.image.set_colorkey(BLACK)
    self.rect = self.image.get_rect()
    self.radius = 20
    self.rect.centerx = WIDTH / 2
    self.rect.bottom = HEIGHT - 10
    self.speedx = 0 
   

    ## unhide 
    if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:
        self.hidden = False
        self.rect.centerx = WIDTH / 2
        self.rect.bottom = HEIGHT - 30

    self.speedx = 0     ## makes the player static in the screen by default. 
    # then we have to check whether there is an event hanlding being done for the arrow keys being 
    ## pressed 

    ## will give back a list of the keys which happen to be pressed down at that moment
    keystate = pygame.key.get_pressed()     
    if keystate[pygame.K_LEFT]:
        self.speedx = -5
    elif keystate[pygame.K_RIGHT]:
        self.speedx = 5

    #Fire weapons by holding spacebar
    if keystate[pygame.K_SPACE]:
        self.shoot()

    ## check for the borders at the left and right
    if self.rect.right > WIDTH:
        self.rect.right = WIDTH
    if self.rect.left < 0:
        self.rect.left = 0

Solution

  • I resolve my problem using this.

    if event.type == pygame.MOUSEMOTION:
            player.rect.topleft = pygame.mouse.get_pos()