Unity四元数保留X、Z旋转:复制目标物体Y轴旋转的代码修改咨询
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
Yrotationtarget. - 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

