Home>

I gave the player character a script to jump and move left and right in Unity, but when it falls off a cliff, it spins and falls off my head.
How can I prevent it from rotating on its own?

The script is as follows.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager: MonoBehaviour
{
    Rigidbody2D rigid2D;
    float jumpForce = 160f;
    float walkForce = 30.0f;
    float maxWalkSpeed ​​= 2.0f;
    private void Start ()
    {
        this.rigid2D = GetComponent<Rigidbody2D>();
    }
    private void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Space))
        {
            this.rigid2D.AddForce (transform.up * this.jumpForce);
        }
        int key = 0;
        if (Input.GetKey (KeyCode.RightArrow))
        {
            key = 1;
        }
        if (Input.GetKey (KeyCode.LeftArrow))
        {
            key = -1;
        }
        // Player speed
        float speedx = Mathf.Abs (this.rigid2D.velocity.x);
        // Speed ​​limit
        if (speedx<this.maxWalkSpeed)
        {
            this.rigid2D.AddForce (transform.right * key * this.walkForce);
        }
        // Invert according to the direction of movement
        if (key! = 0)
        {
            transform.localScale = new Vector3 (key, 1, 1);
        }
    }
}
code
  • Answer # 1

    I checked the freez rotation of Rigid Body 2D and it was fixed.

  • Answer # 2

    I checked the freez rotation of Rigid Body 2D and it was fixed.