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

Ursina Engine立方体自适应地形旋转异常问题求助

立方体自适应地形旋转问题修复方案

问题根源分析

你的代码存在以下核心问题导致立方体旋转异常:

  • 射线检测起点错误:从立方体中心而非底部发射射线,导致高度计算偏差
  • 法线目标点计算错误:normal = cubeObject.position + hit_info.normal 生成的目标点不符合旋转需求,导致look_at逻辑混乱
  • 旋转赋值方式错误:直接复制父物体的x/z旋转,易引发万向锁问题,无法正确贴合地形法线
  • 内存泄漏:每次update都创建新调试球体,会导致性能急剧下降

修复后的完整代码

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()

# 创建地形
terrain = Entity(model=Terrain('heightmap', skip=4), scale=(128, 20, 128), texture='grass', collider='mesh', debug=True)
terrain.y -= 5

# 创建玩家
player = FirstPersonController()
player.y = 5

# 创建自适应立方体
cubeObject = Entity(model="cube", scale=(2,1,2), color=color.yellow, position=(0,5,0))

# 调试用球体(仅创建一次)
debug_normal_sphere = Entity(model="sphere", scale=0.3, color=color.red, enabled=False)
debug_cube_sphere = Entity(model="sphere", scale=0.3, color=color.blue, enabled=False)

def update():
    # 从立方体底部中心发射射线,检测下方地形
    ray_start = cubeObject.world_position - Vec3(0, cubeObject.scale_y/2, 0)
    hit_info = raycast(ray_start, Vec3(0,-1,0), ignore=(cubeObject,), distance=2, debug=True)

    if hit_info.hit:
        # 将立方体移动到地形表面上方(底部贴合地形)
        cubeObject.y = hit_info.point.y + cubeObject.scale_y/2

        # 让立方体的up方向对齐地形法线,实现贴合旋转
        cubeObject.rotation = Vec3(0,0,0).rotation_from_vectors(Vec3(0,1,0), hit_info.normal)

        # 更新调试球体位置(可选)
        debug_normal_sphere.enabled = True
        debug_normal_sphere.position = hit_info.point + hit_info.normal
        debug_cube_sphere.enabled = True
        debug_cube_sphere.position = cubeObject.position

    else:
        # 未检测到地形时下落
        cubeObject.y -= 3 * time.dt
        # 恢复默认旋转
        cubeObject.rotation = Vec3(0,0,0)
        # 关闭调试球体
        debug_normal_sphere.enabled = False
        debug_cube_sphere.enabled = False

app.run()

关键修改说明

  • 射线起点修正:从立方体底部中心发射射线,确保准确检测下方地形的接触点
  • 位置校准:命中地形时,将立方体高度设置为hit_info.point.y + 半高,保证底部完全贴合地形
  • 旋转逻辑优化:使用rotation_from_vectors直接将立方体的默认up方向(0,1,0)对齐地形法线,避免万向锁和无规则旋转
  • 调试资源优化:仅创建一次调试球体,通过enabled控制显示,避免内存泄漏
  • 下落状态处理:未检测到地形时恢复默认旋转,避免悬空时保持异常姿态

内容的提问来源于stack exchange,提问作者james strand 123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:03:24