行星模拟项目中轨道轨迹位置偏移问题求助
行星轨道轨迹偏移问题修复方案
问题根源
当前轨迹记录的是行星矩形的左上角坐标,但行星的实际运动中心是图像的几何中心,导致轨迹与行星本体错位,无法贴合行星后方。
具体修复步骤
1. 修正轨迹记录的坐标(核心修复)
修改trail函数,将记录的左上角坐标替换为行星图像的中心坐标:
trail_d = {} def trail(n, planet_obj, color): if n not in trail_d: trail_d[n] = [] # 计算行星图像的中心坐标(替换原左上角坐标) center_x = planet_obj[1].x + planet_obj[0].get_width() // 2 center_y = planet_obj[1].y + planet_obj[0].get_height() // 2 trail_d[n].append((center_x, center_y)) # 至少2个点才绘制轨迹,避免报错 if len(trail_d[n]) >= 2: pygame.draw.aalines(screen, color, False, trail_d[n]) # 限制轨迹长度,超出部分移除最早的点 if len(trail_d[n]) > planet_data[n][0]: trail_d[n].pop(0)
2. 同步行星位置计算逻辑(可选,让轨道数学更严谨)
在revolve函数中,先计算行星中心的轨道位置,再反推矩形左上角坐标,确保行星中心严格沿轨道运动:
def revolve(n): x,y,theta,inc,color = planet_data[n] planet_obj = planets[f'planet{n}'] # planet_surf, planet_rect # 先计算行星中心的轨道坐标 center_x = x * math.cos(theta) + h center_y = y * math.sin(theta) + k # 反推矩形左上角位置(让中心对齐轨道点) planet_obj[1].x = center_x - planet_obj[0].get_width() // 2 planet_obj[1].y = center_y - planet_obj[0].get_height() // 2 theta -= inc planet_data[n][2] = theta trail(n, planet_obj, color) screen.blit(planet_obj[0], planet_obj[1])
3. 移除冗余的try-except块
原代码中的空except块会隐藏潜在错误,改用显式的存在性检查(如if n not in trail_d)更安全。
内容的提问来源于stack exchange,提问作者abduco
相关产品推荐
相关产品推荐

