Search code examples
c#unity-game-engine

why when moving the player character to the left the player seems like the character is behind/inside objects but to the right it's fine?


using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float rotationSpeed = 10f;
    private Rigidbody rb;
    private Animator animator;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        // Handle animations in Update
        float moveX = Input.GetAxis("Horizontal");
        animator.SetFloat("Speed", Mathf.Abs(moveX * moveSpeed)); // Ensure Speed is a positive value
        animator.SetBool("Grounded", true); // Assuming the player is always grounded in this example
    }

    void FixedUpdate()
    {
        // Handle physics in FixedUpdate
        float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.fixedDeltaTime;

        // Move the player only on the x-axis
        Vector3 newPosition = rb.position + new Vector3(moveX, 0f, 0f);
        rb.MovePosition(newPosition);

        // Rotate to face the direction of movement
        if (moveX != 0)
        {
            Vector3 targetDirection = new Vector3(moveX, 0f, 0f);
            Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
            rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
        }
    }
}

screenshot showing when i press the A key to the left.

moving the player to the left

and when moving to the right it's fine:

when moving to the right the player is in front everything as it should be.

screenshot of the player settings in the inspector:

player settings

and the animator controller of the player with the blend tree and parameters settings:

animation controller settings


Solution

  • 1- make sure your "order in layer" property for your player sprites are higher than environment.

    or

    2- better, put all of them in a "sorting layer" and put that layer in front of environment layer.

    there is a "order in layer" and a "sorting layer" property in sprite component. to determine which object is in front or behind unity uses these two. layers are self explanatory and they have a order. so for example you make a UI layer and put your UI in it so it always appear in front of everything. "order in layer" is similar but in layers.