You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame使用blit绘制时敌方角色到达目标位置后图像消失问题

错误原因分析

1. 绘制逻辑分支缺失(直接导致敌方消失)

你所有的blit绘制代码全部封装在x轴移动判断的两个分支内:

  • 当player.x + self.offset_x > self.x - display_scroll[0](x轴目标在右侧)
  • 当player.x + self.offset_x < self.x - display_scroll[0](x轴目标在左侧)
    当敌方到达x轴目标点,也就是player.x + self.offset_x == self.x - display_scroll[0]时,两个分支都不会触发,完全没有执行绘制代码,因此敌方直接消失。

2. 到达目标点的判断存在变量拼写错误

你写的目标点命中条件为:
player.y + self.offset_y == self.y - display_scroll[1] and player.x + self.offset_y == self.x - display_scroll[0]
第二个判断项错误将offset_x写成了offset_y,导致哪怕x、y都到达目标位置,也大概率无法命中这个条件,触发静止显示第一帧的逻辑。

3. y轴移动逻辑存在变量拼写错误

y轴移动的第二个判断分支写为:
elif player.y + self.offset_x < self.x-display_scroll[1]:
存在两个错误:

  • 错误使用了x轴偏移offset_x计算y轴目标位置
  • 错误将敌方y坐标self.y写成了self.x
    会导致敌方y轴移动逻辑异常,无法正确到达y轴目标点。

修复建议

将绘制逻辑从x轴移动判断分支中抽出来,放到所有移动逻辑之后,同时修正所有变量拼写错误即可解决问题,参考修复代码:

def main(self, display):
    if self.animation_count + 1 >= 16:
        self.animation_count = 0
    self.animation_count += 1

    if self.reset_offset == 0:
        self.offset_x = randrange(-150, 150)
        self.offset_y = randrange(-150, 150)
        self.reset_offset = randrange(120, 150)
    else:
        self.reset_offset -= 1

    # 修正y轴移动逻辑
    target_y = player.y + self.offset_y
    current_screen_y = self.y - display_scroll[1]
    if target_y > current_screen_y:
        self.y += 1
    elif target_y < current_screen_y:
        self.y -= 1

    target_x = player.x + self.offset_x
    current_screen_x = self.x - display_scroll[0]
    flip = False
    if target_x > current_screen_x:
        self.x += 1
    elif target_x < current_screen_x:
        self.x -= 1
        flip = True

    # 统一绘制逻辑,确保每一帧都执行
    if target_y == current_screen_y and target_x == current_screen_x:
        # 到达目标点,固定显示第一帧
        img = self.animation_images[0]
    else:
        img = self.animation_images[self.animation_count // 4]
    if flip:
        img = pygame.transform.flip(img, True, False)
    display.blit(pygame.transform.scale(img, (32, 42)), (current_screen_x, current_screen_y))

内容的提问来源于stack exchange,提问作者Jerry Cui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:06:00