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

Unity四元数保留X、Z旋转:复制目标物体Y轴旋转的代码修改咨询

Fix for Preserving X/Z Rotation While Syncing Y-Axis

Got it, let's sort this out! The issue with your current code is that you're creating a brand new Quaternion from scratch with X and Z set to 0, which completely overwrites the existing X/Z rotation of your rigidbody. Instead, we need to keep the current X and Z rotation values and only update the Y axis to match your target Yrotation object.

Here's the modified code that does exactly that:

public class LockRotation : MonoBehaviour 
{
    Rigidbody m_Rigidbody; 
    public Transform Yrotation; 

    void Start() 
    {
        m_Rigidbody = GetComponent<Rigidbody>(); 
    }

    void FixedUpdate() 
    {
        // Get the current Euler angles of the rigidbody, preserving X and Z
        Vector3 currentRotation = m_Rigidbody.rotation.eulerAngles;
        // Update only the Y axis to match the target object's Y rotation
        currentRotation.y = Yrotation.rotation.eulerAngles.y;
        // Convert back to Quaternion and apply to the rigidbody
        m_Rigidbody.MoveRotation(Quaternion.Euler(currentRotation));
    }
}

How This Works:

  • We first grab the current rotation state of your rigidbody using eulerAngles—this gives us the existing X, Y, Z values.
  • We replace only the Y component of that vector with the Y rotation from your Yrotation target.
  • Convert the modified Euler angles back to a Quaternion (since Rigidbody uses Quaternions for rotation to avoid gimbal lock) and apply it with MoveRotation.

If you prefer working directly with Quaternions (to avoid any potential Euler angle edge cases), you can also use this approach to combine rotations:

void FixedUpdate() 
{
    // Extract the X/Z rotation from the rigidbody (ignore Y)
    Quaternion xzRotation = Quaternion.Euler(
        m_Rigidbody.rotation.eulerAngles.x, 
        0, 
        m_Rigidbody.rotation.eulerAngles.z
    );
    // Extract only the Y rotation from the target object
    Quaternion targetYRotation = Quaternion.Euler(0, Yrotation.rotation.eulerAngles.y, 0);
    // Combine the X/Z rotation with the target Y rotation
    m_Rigidbody.MoveRotation(xzRotation * targetYRotation);
}

Both approaches will keep your object's original X and Z rotation intact while syncing the Y axis to your target transform.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:20:42