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

Ursina/Python:如何让update()基于坐标而非时间修改天体位置

Ursina实现预设坐标更新地月日位置方案

核心思路是用预计算的轨迹数组,配合计时器同步时间步,在update()中直接给天体实体赋值对应坐标,替代原有的旋转逻辑。

具体实现步骤

  1. 准备你的轨迹数组:确保每一行对应[sun_x,sun_y,earth_x,earth_y,moon_x,moon_y],和计算时的dt=0.1时间步匹配。
  2. 创建Ursina天体实体:用Entity或Sphere定义太阳、地球、月球的视觉样式。
  3. 用计时器控制步长:避免按帧跳步,保证动画速度和计算时的时间步一致。
  4. 在update()中更新坐标:根据当前时间步索引,从数组中取坐标赋值给天体的x/y属性。

完整代码示例

from ursina import *

app = Ursina()

# 替换成你自己计算好的轨迹数组,这里是模拟示例数据
trajectories = [
    [0, 0, 10, 0, 12, 0],
    [0, 0, 9.8, 1.98, 11.76, 2.38],
    [0, 0, 9.2, 3.8, 11.04, 4.56],
    [0, 0, 8.2, 5.4, 9.84, 6.48],
    [0, 0, 6.8, 6.6, 8.16, 7.92],
    [0, 0, 5, 7.4, 6.0, 8.88],
    # ... 补充你所有计算好的时间步坐标
]

# 创建天体:设置模型、颜色、缩放(可根据需求调整)
sun = Entity(model='sphere', color=color.yellow, scale=2, z=0)
earth = Entity(model='sphere', color=color.blue, scale=1, z=0)
moon = Entity(model='sphere', color=color.gray, scale=0.5, z=0)

current_step = 0
timer = 0.0
calc_dt = 0.1  # 和你计算轨迹时用的时间步保持一致

def update():
    global current_step, timer
    timer += time.dt  # 累加当前帧的真实时间
    
    # 当累计时间达到计算时的dt,更新位置
    if timer >= calc_dt:
        timer -= calc_dt  # 重置计时器,处理帧时间误差
        
        # 取出当前时间步的坐标
        sun_x, sun_y, earth_x, earth_y, moon_x, moon_y = trajectories[current_step]
        
        # 直接赋值坐标(如果需要3D效果,可添加z轴值)
        sun.position = (sun_x, sun_y, 0)
        earth.position = (earth_x, earth_y, 0)
        moon.position = (moon_x, moon_y, 0)
        
        # 循环播放轨迹,若要单次播放可改为:current_step = min(current_step+1, len(trajectories)-1)
        current_step = (current_step + 1) % len(trajectories)

app.run()

关键细节说明

  • 坐标缩放:如果你的计算坐标数值太小,天体可能重叠,可给坐标乘一个缩放因子(比如sun_x * 2)调整视觉效果。
  • 时间同步:用time.dt累加真实时间,保证动画速度和你计算时的dt=0.1完全匹配,避免帧率波动导致的速度偏差。
  • 停止/循环:代码默认循环播放轨迹,若要播放一次后停止,把步数更新逻辑改成current_step = min(current_step+1, len(trajectories)-1)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:45:20