[英]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.