PyGame方向检测异常:为何始终输出Left?
问题描述
使用Python结合PyGame开发游戏时,尝试通过比较玩家的X坐标与鼠标的X坐标来检测方向,但输出始终为Left。相关错误代码片段:
if x > mpos[1]: print("Left") if x < mpos[1]: print("Right")
完整代码如下:
import pygame import random pygame.init() window = pygame.display.set_mode([1920,1000]) pygame.display.set_caption('Bouncy Ball') x = 1920 / 2 y = 1000 / 2 count = 0 aft = False xbox1 = random.randint(0,1920) ybox1 = -30 game = True while game: for event in pygame.event.get(): if event.type == pygame.QUIT: game = False window.fill((255,255,255)) player = pygame.Rect(x - 128, y - 128, 128, 128) platform = pygame.Rect(xbox1 - 30, ybox1 - 128, 256, 60) pygame.draw.rect(window, (0,0,255), player) pygame.draw.rect(window, (255,0,0), platform) pygame.event.get() mse = pygame.mouse.get_pressed() if mse[0] == True: mpos = pygame.mouse.get_pos() pygame.draw.circle(window, (175,175,175), (mpos[0], mpos[1]), 64) force = abs(mpos[0] - x - 128 + mpos[1] - y - 128) / 100 aft = True if mse[0] == False: if aft: if x > mpos[1]: print("Left") if x < mpos[1]: print("Right") print(mpos) print((x,y)) aft = False pygame.display.flip() ybox1 = ybox1 + 1 if ybox1 == 1060: ybox1 = -30 xbox1 = random.randint(0,1920) y = y + count if count < 5: count = count + 1 if y >= 1100: y = 1000 / 2 pygame.quit()
需求是找到正确方向判断逻辑,让玩家能够飞向目标平台,已确认坐标值输出正确,但方向判断始终错误。
解决方案
核心错误是误用了鼠标坐标的索引:pygame.mouse.get_pos()返回的是(X坐标, Y坐标)的元组,你用mpos[1](鼠标Y坐标)和玩家X坐标x做比较,这是不同维度的数值对比,必然得到错误的方向结果。
修正后的方向判断代码应该用mpos[0](鼠标X坐标):
if mse[0] == False: if aft: # 用鼠标X坐标(mpos[0])和玩家X坐标(x)比较 if x > mpos[0]: print("Left") elif x < mpos[0]: print("Right") else: print("Same X position") print(mpos) print((x,y)) aft = False
另外补充两个优化点:
- 代码中重复调用了
pygame.event.get(),第一次在事件循环里,第二次在绘制之后,这会导致部分事件被丢弃(比如QUIT事件可能无法被正确捕获),建议移除第二处的pygame.event.get()。 - 玩家的碰撞矩形是
pygame.Rect(x - 128, y - 128, 128, 128),说明x和y是玩家矩形的中心坐标,如果需要更精准的方向判断(比如基于玩家边缘),可以用player.centerx或者player.left/player.right来替代x做比较。
内容的提问来源于stack exchange,提问作者MiguelCodes
相关产品推荐
相关产品推荐

