Hello Goodnight. I have a question about programming player movements. When my character jumps, he sometimes "spins" and falls "lying down" instead of getting firm to the floor or platform. Also, when it falls down a cliff, it spins in the air, and therefore falls back down. You can see the behavior in the video linked to this topic. The ideal behavior should be like when Samus (Metroid) or Mario (Super Mario) jump and fall "standing up", they don't go straight. Like the impulse exceeds my character. Similarly, on a sloping floor, my character instead of going down "correctly", rolls down. In the following video, we can see Samus correctly lower sloping floors, fall vertically in the cliffs and jump correctly. As you can see, it is a testing version that I am trying to improve. Here my code: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterMovement : MonoBehaviour { Rigidbody2D rbd2; /* * Movimientos básicos. */ public float Speed = 10.0f; public float jumpForce = 300.0f; public bool facingRight = true; /* * Verificamos si el personaje está en contacto con el suelo. */ public Transform groundCheck; public float groundRadius = 0.2f; public bool grounded = false; public LayerMask whatIsGround; // Start is called before the first frame update void Start() { } // Update is called once per frame void FixedUpdate() { float move = Input.GetAxis("Horizontal"); if (move < 0) GetComponent<Rigidbody2D>().velocity = new Vector3(move * Speed, GetComponent<Rigidbody2D>().velocity.y); if (move > 0) GetComponent<Rigidbody2D>().velocity = new Vector3(move * Speed, GetComponent<Rigidbody2D>().velocity.y); if (move < 0 && facingRight) Flip(); if (move > 0 && !facingRight) Flip(); bool jump = Input.GetButtonDown("Jump"); grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround); if (jump && grounded) GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumpForce); } void Flip() { facingRight = !facingRight; transform.Rotate(Vector3.up * 180); } } How I can fix these details?
Try setting your Rigidbody2D component's constraints in the inspector, lock the Z rotation. If you would rather change it in code, you can use rb2d.constraints = RigidbodyConstraints2D.freezeRotation; In your code, you can assign rb2d once in the Start method using GetComponent<Rigidbody2D>(). Then everywhere else you can use rb2d variable instead of calling GetComponent each time.
Ok! Thanks for answer jeffreyschoch! How is better? Change it in inspector or by code? Is there a difference or best practice? Regards!!
No difference, you can change it in the inspector and be done with it. Unless if for some reason you want to unfreeze your character's Z constraint somewhere during runtime then you do it by code.