2
\$\begingroup\$

So I am looking to freeze rotation in the Y axis on a Rigidbody 2D. I'm not sure how to set this in my code. This is what I have so far, can you point out my errors?

public class PlayerMovement : MonoBehaviour 
{

    public float speed;
    public float height;
    GameObject Player;
    RigidbodyConstraints pos;
    Transform P;
    // Update is called once per frame

    void OnAwake()
    {
        Player = GameObject.Find ("Player");
        pos = RigidbodyConstraints.FreezeRotationY;
        Rigidbody2D. = pos;
    }


    void FixedUpdate () 
    {
        if (Input.GetButton ("Horizontal")) 
        {
            transform.Translate (Vector3.right * speed * Time.deltaTime);
        }

        if( Input.GetButton("Left"))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }

        if (Input.GetButton ("Jump")) 
        {
            transform.Translate (Vector3.up * height * Time.deltaTime);
        }


    }
}
\$\endgroup\$
4
\$\begingroup\$

First of all, since you're working in 2D, you'll want to use the type RigidbodyConstraints2D as opposed to just RigidbodyConstraints.

Secondly, you can't freeze the y rotation on 2D rigidbodies, only in the z axis, which you can do by saying:

pos = RigidbodyConstraints2D.FreezeRotation;

Equally, you could just set it in the inspector with the gameobject selected, which would save you the hassle of all this code.

Lastly, Rigidbody2D. = pos; in your OnAwake() function, which by the way should just be Awake(), isn't doing anything. In Unity 5 you can't call the rigidbody directly anymore, you have to find the component.

I'll leave this here to get you on the right track. :)

Good Luck and keep at it!

\$\endgroup\$
1
\$\begingroup\$

Expanding upon Anthony Ngo's answer

As of Unity 5.1 you can simply do it in the editor:

enter image description here

Source: http://unity3d.com/unity/whats-new/unity-5.1 To get to that part you can probably do Ctrl + F then type rigidbody. Your browser should then highlight that part.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.