Pygame游戏中出现「TypeError: integer argument expected, got float」的原因?
解决Pygame中
get_at()抛出「TypeError: integer argument expected, got float」的问题 嘿,这个问题我之前做2D平台游戏的时候也踩过坑!咱们来一步步解决它:
问题根源
pygame.Surface.get_at()这个方法要求传入的坐标必须是整数——毕竟屏幕上的像素都是离散的,不存在“半像素”的位置。你代码里的player["x"]、player["y"]这些变量大概率是浮点数(比如为了实现平滑移动,你可能用了player["x"] += 0.3这样的逻辑),直接把浮点数传给get_at()自然就会触发类型错误。
解决方案
最直接的办法就是把浮点数坐标转换成整数,这里有两种常用方式,你可以根据需求选:
1. 截断小数部分(用int())
这是最常用的方式,直接把小数部分砍掉,相当于向0取整:
# 先初始化默认状态 leftOfPlayerOnPlatform = True rightOfPlayerOnPlatform = True # 把坐标转成整数 left_foot_pos = (int(player["x"]), int(player["y"] + player["height"])) right_foot_pos = (int(player["x"] + player["width"]), int(player["y"] + player["height"])) if surface.get_at(left_foot_pos) == (0, 0, 0, 255): leftOfPlayerOnPlatform = False if surface.get_at(right_foot_pos) == (0, 0, 0, 255): rightOfPlayerOnPlatform = False # 补全你没写完的逻辑 if not leftOfPlayerOnPlatform and not rightOfPlayerOnPlatform: # 比如让玩家下落 player["y"] += gravity
2. 四舍五入(用round())
如果你希望坐标更贴合视觉上的位置,可以用round()把浮点数转成最接近的整数:
left_foot_pos = (round(player["x"]), round(player["y"] + player["height"])) right_foot_pos = (round(player["x"] + player["width"]), round(player["y"] + player["height"]))
额外优化建议
频繁调用get_at()其实性能不太行,因为它每次都要直接访问像素数据。如果你的平台是规则形状的,建议改用pygame.Rect来做碰撞检测——比如把玩家和平台都定义成Rect对象,然后用colliderect()或者collidepoint()来判断,效率会高很多,代码也更简洁。
举个例子:
# 定义玩家Rect player_rect = pygame.Rect(player["x"], player["y"], player["width"], player["height"]) # 定义平台Rect(假设平台数据存在platforms列表里) for platform in platforms: platform_rect = pygame.Rect(platform["x"], platform["y"], platform["width"], platform["height"]) # 检查玩家底部是否碰到平台顶部 if player_rect.colliderect(platform_rect) and player_rect.bottom <= platform_rect.top + 5: # 玩家站在平台上,取消下落 leftOfPlayerOnPlatform = True rightOfPlayerOnPlatform = True break else: # 没碰到任何平台,下落 leftOfPlayerOnPlatform = False rightOfPlayerOnPlatform = False
内容的提问来源于stack exchange,提问作者Formula 1
相关产品推荐
相关产品推荐

