簡體   English   中英

Python / Pygame鼠標位置不更新(空白功能)

[英]Python/Pygame mouse position does not update (blit function)

我正在嘗試使用Pygame制作一個簡單的菜單,但是我發現,每當我使用pygame.mouse.get_position時,它確實會弄亂我想要的東西,但是我必須不斷移動鼠標以使我的圖片保持閃爍狀態。

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('cursor test')

cursorPng = pygame.image.load('resources/images/cursor.png')
start = pygame.image.load('resources/images/menuStart.jpg')
enemy = pygame.image.load('resources/images/enemy-1.png')

white = (255,255,255)
black = (0,0,0)

clock = pygame.time.Clock()
FPS = 60

while True:
    screen.fill(white)
    pygame.mouse.set_visible(False)

    x,y = pygame.mouse.get_pos()
    x = x - cursorPng.get_width()/2
    y = y - cursorPng.get_height()/2
    screen.blit(cursorPng,(x,y))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

        elif event.type == pygame.MOUSEMOTION:
            if x < 50 and y < 250:
                screen.blit(enemy,(100,100))

    clock.tick(FPS)
    pygame.display.update()

怎么了?

看一下您的代碼:

for event in pygame.event.get():
    ...
    elif event.type == pygame.MOUSEMOTION:
        if x < 50 and y < 250:
            screen.blit(enemy,(100,100))

您檢查事件,如果您檢測到鼠標(並且僅此后)被移動,則將圖像繪制到屏幕上。

如果即使不移動鼠標也要繪制圖像,則只需停止檢查MOUSEMOTION事件,然后總是繪制圖像即可:

while True:
    screen.fill(white)
    pygame.mouse.set_visible(False)

    x,y = pygame.mouse.get_pos()
    x = x - cursorPng.get_width()/2
    y = y - cursorPng.get_height()/2
    screen.blit(cursorPng,(x,y))
    if x < 50 and y < 250:
        screen.blit(enemy,(100,100))

    for event in pygame.event.get():
        ...

您需要將“曲面”和“矩形”拖入屏幕。

首先,使用我用於加載圖像的代碼段。 確保圖像正確加載:

def loadImage(name, alpha=False):
"Loads given image"

    try:
        surface = pygame.image.load(name)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s' %
                     (name, pygame.get_error()))
    if alpha:
        corner = surface.get_at((0, 0))
        surface.set_colorkey(corner, pygame.RLEACCEL)

    return surface.convert_alpha()

其次,當您獲得Surface時,請像這樣獲得其矩形:

cursorSurf = loadImage('resources/images/cursor.png')
cursorRect = cursorSurf.get_rect()

然后,在更新中執行以下操作:

cursorRect.center = pygame.mouse.get_pos()

最后,像這樣流血到屏幕:

screen.blit(cursorSurf, cursorRect)

現在,您將注意到鼠標的正確渲染,而無需移動鼠標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM