使用collidepoint函数时鼠标无法与Pygame对象正确交互的问题
解决Pygame自定义Surface上鼠标碰撞检测失效的问题
问题根源
你的player_rect和barrier_1_rect是基于自定义Surface的局部坐标系计算的,但pygame.mouse.get_pos()获取的是屏幕全局坐标系的位置,两者不在同一坐标系下,导致碰撞检测永远不触发。
自定义Surface在屏幕上的偏移量是(midalignX_lg, midalignY_lg),必须把其中一方的坐标转换到另一方的坐标系中才能正确检测碰撞。
两种可行解决方案
方案1:将鼠标坐标转换为Surface局部坐标
计算鼠标在自定义Surface内的相对位置,再用这个位置做碰撞检测:
# 替换原碰撞检测代码 A = False mouse_pos = pygame.mouse.get_pos() # 转换为Surface局部坐标 local_mouse_x = mouse_pos[0] - midalignX_lg local_mouse_y = mouse_pos[1] - midalignY_lg local_mouse_pos = (local_mouse_x, local_mouse_y) if player_rect.collidepoint(local_mouse_pos): A = True
方案2:将对象Rect转换为屏幕全局坐标
把player_rect偏移到屏幕坐标系下,再和鼠标位置检测碰撞:
# 替换原碰撞检测代码 A = False mouse_pos = pygame.mouse.get_pos() # 计算对象在屏幕上的实际Rect screen_player_rect = player_rect.move(midalignX_lg, midalignY_lg) if screen_player_rect.collidepoint(mouse_pos): A = True
额外优化建议
你在主循环里每次都重新创建surface = pygame.Surface((w_surface,h_surface)),这会浪费性能。建议只在初始化时创建一次Surface,循环内只做填充和绘制:
# 初始化时创建一次 surface = pygame.Surface((w_surface,h_surface)) while True: # ... 事件处理 ... # 循环内只填充和绘制 surface.fill('Light Yellow') surface.blit(barrier_1_surf, barrier_1_rect) surface.blit(player_surf, player_rect) screen.blit(surface, (midalignX_lg,midalignY_lg)) # ... 其他绘制和逻辑 ...
内容的提问来源于stack exchange,提问作者vypexe
相关产品推荐
相关产品推荐

