Search code examples
c#unity-game-enginerotationquaternionseuler-angles

How to freeze rotation in the z & y axes directions? Unity3D


I have a platform that can swing on a wide cylinder if objects are unevenly distributed on it.

To do this, I created a cylinder with a mesh collider, put a platform on top of it, whose centers coincide with each other.

Then I attached a code to the platform that freezes its position, that is, the platform can now only rotate, but not fall.

Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DeterminantOfPlatformEquilibrium : MonoBehaviour
{
   Vector3 newYPos;

    void Start()
    {
    newYPos = transform.position;
    }

    void Update()
    {
        /*We're setting the position of the object in the
        "y" direction - unchanged, and equal to zero, 
        so that the platform does not fall becaude of gravity*/
newYPos.y += 0.0f;
transform.position = newYPos;
newYPos += new Vector3(0f, 0f, 0f);

    }
}

In addition to freezing the position of the platform, I must also freeze its rotations in the y & z directions, so that it rotates in only one direction - in x.

I tried to do this using the call to the Euler () method from the Quaternion class, set a certain angle of rotation to the x axis, and set the other 2 axes to zero, and it seemed to me that everything should work, but this line does not seem to do anything in my code: Quaternion rotation = Quaternion.Euler(23f, 0f, 0f);

Do you have more possible options for freezing these 2 axes?


Solution

  • Freeze All Rotation

        rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
    

    Freeze Specific Rotation:

        rigidbody.constraints = RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
    

    You can find view Unity Documentation , but they did not explained it well