I couldnt get Rigidbody to freeze X

I am trying to freeze the x value after the player dies because he just starts to slide even if the movement script is disabled i searched the documents but i couldnt really understand it

using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
    [SerializeField]private float startingHealth;
    public float currentHealth { get; private set; }
    private Animator anim;
    private bool dead;
    public RigidbodyConstraints2D const;

    private void Awake()
    {
        currentHealth = startingHealth;
        anim = GetComponent<Animator>();
        const = GetComponent<RigidbodyConstraints2D>();
    }
   
   

    public void TakeDamage(float _damage)
    {
        currentHealth = Mathf.Clamp(currentHealth - _damage, 0, startingHealth);

        if(currentHealth > 0)
        {
            anim.SetTrigger("hurt");
        }else{
            if(!dead){
                anim.SetTrigger("die");
                RigidbodyConstraints2D.FreezeAll;
                GetComponent<PlayerMovement>().enabled = false;
                dead = true;
               
            }
           
        }
    }
}

If you have a better method of stopping the player after dying please share it

I dont understand why you are getting the RigidbodyConstraints component instead of just the rigidbody itself. I would guess switch that and then do like Rigidbody.constraints RigidbodyConstraints.FreezePositionX

Look here: Unity - Scripting API: Rigidbody.constraints (unity3d.com)

I’m not entirely sure if this would work, but could you just do:

public Rigidbody2D rbname;

//When dead (not !dead, which means you’re still alive):

rbname.enabled = false;

Either reset its linear velocity or just turn-off its simulation.

This is a great idea but unfortunately Rigidbody does not inherit from that lineage and has no .enabled field.

Some other options:

  • Destroy() the Rigidbody instance

  • set it to .isKinematic = true

  • use a FixedJoint and pin it in place

1 Like

Sorry, my mistake. I’ve been using the .enabled field in my project with a Collider2D, not a rigidbody.