George B George B - 3 months ago 21
C# Question

How do I freeze rotation of a Rigidbody programatically?

I am creating a 2D platformer game, and I already wrote the script that moves the sprite forwards and backwards successfully. However, I am extremely new to Unity and C#, so I have no idea how to freeze rotation of the sprite.

I tried to do it programatically (because the use gravity option did not appear in inspector) like so-

void Update () {

anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));

rb2d.freezeRotation.freezeRotation = true;

}


but it obviously doesn't work. How do I correctly freeze rotation of the sprite with c#? Where do I put this code?

Thanks in advance-
George :)

Answer

What you could do to constraint the rotation on one axis of your object is:

  • Create a variable float freezeRotationX = 5.0f; //5.0 is just an example

  • And write this transfrom.rotation = Quaternion.Euler(freezeRotationX, transfrom.rotation.y, transfrom.rotation.z); This line should be in the Update methode.

This will fix the rotation on the X axis and leave the other ones with their current value. Of course you can create a variable for each axis.

Hope that helps you.

Comments