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

quaternion四元数Y轴额外旋转实现方案及移动转向代码问题咨询

实现方案

你只需要在Quaternion.LookRotation计算得到面朝移动方向的目标旋转后,叠加一个绕Y轴旋转90度的四元数即可,注意Unity中四元数的乘法顺序,叠加局部偏移旋转要放在原旋转的右侧。

修改后的核心代码

float speed = 20.0f;
float rSpeed = 200.0f;

// Start is called before the first frame update
void Start()
{
}

// Update is called once per frame
void Update()
{
    float xValue = Input.GetAxis("Horizontal");
    float zValue = Input.GetAxis("Vertical");
    float yValue = 0;
    Vector3 movementDir = new Vector3(xValue,yValue,zValue);
    movementDir.Normalize();

    transform.Translate(movementDir * speed * Time.deltaTime, Space.World);

    if (movementDir != Vector3.zero)
    {
        Quaternion toRotation = Quaternion.LookRotation(movementDir, Vector3.up);
        // 额外叠加Y轴90度旋转
        toRotation *= Quaternion.Euler(0, 90f, 0);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rSpeed * Time.deltaTime);
    }
}

如果测试后发现旋转方向反向,把90f改为-90f即可。


其他可行的实现方法

  • 提前旋转移动方向向量
    调用LookRotation之前先把移动方向绕Y轴旋转90度,效果和叠加四元数完全等价:
    Vector3 rotatedMoveDir = Quaternion.Euler(0,90f,0) * movementDir;
    Quaternion toRotation = Quaternion.LookRotation(rotatedMoveDir, Vector3.up);
    
  • 节点层级拆分法
    给当前对象添加一个父节点,移动和转向逻辑挂在父节点上,模型挂在子节点上,直接把带子节点的localRotation设置为(0,90,0)即可。这种方法不需要修改逻辑代码,后续调整偏移角度更灵活,适合逻辑和表现分离的项目。

注意事项

不要直接修改transform.rotation.eulerAngles的Y值,四元数转欧拉角的过程中可能出现万向锁、数值跳变的问题,叠加旋转优先使用四元数乘法。

内容的提问来源于stack exchange,提问作者Ethan St John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:36:07