在pygame上实现鼠标移动

时间:2017-06-15 03:32:16

标签: python pygame 2d-games

我正在研究太空射击游戏的克隆,我需要用鼠标移动玩家,现在玩家正在按箭头键移动到左右键。

这是我代码的一个片段。

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

3 个答案:

答案 0 :(得分:2)

我使用此解决了我的问题。

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

答案 1 :(得分:1)

你可以使用

self.rect.center (or assign as you wish) = pygame.mouse.get_pos()

这会给你(x,y)鼠标,然后将播放器坐标设置为此值

使用它来使鼠标在pygame窗口中不可见,否则你将看到指针和播放器

pygame.mouse.set_visible(False)

答案 2 :(得分:1)

使用以下代码进行鼠标移动或单击

if pygame.event.get() == MOUSEMOTION:
   x,y=mousex,mousey=event.pos
elif event.type == MOUSEBUTTONUP:
   mousex,mousey=event.pos
   mouseClicked = True