Hello, back with day 3 progress. Today I worked on creating the player's house interior and solved a rendering issue that was driving me crazy. Well I guess it's more of a noob problem but it still made me happy to fix
House Interior: Started building out the inside of the PlayerHouse scene. Added furniture and decorations - nothing fancy yet, but it's starting to feel like a home.
The Tree Problem: Ran into the 2D issue where the player would render in front of trees when they should be behind them, and vice versa.
using UnityEngine; public class YPositionSorting : MonoBehaviour { [Header("Sorting Settings")] [SerializeField] private float yOffset = 0f; [SerializeField] private float sortingMultiplier = 100f; [SerializeField] private int baseSortingOrder = 0; [Header("Optional Settings")] [SerializeField] private bool useCustomPivot = false; [SerializeField] private Vector2 customPivotOffset = Vector2.zero; private SpriteRenderer spriteRenderer; void Start() { spriteRenderer = GetComponent<SpriteRenderer>(); } void Update() { // Calculate Y position with offset float yPosition = transform.position.y + yOffset; // Use custom pivot point if enabled (useful for tall sprites) if (useCustomPivot) { yPosition = transform.position.y + customPivotOffset.y; } // Lower Y position = higher sorting order (appears in front) spriteRenderer.sortingOrder = baseSortingOrder + Mathf.RoundToInt(-yPosition * sortingMultiplier); } // Visual debug in Scene view void OnDrawGizmosSelected() { Vector3 sortingPoint = transform.position; if (useCustomPivot) { sortingPoint += (Vector3)customPivotOffset; } else { sortingPoint.y += yOffset; } // Draw a small sphere at the actual sorting position Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(sortingPoint, 0.1f); // Draw a line from object to sorting point Gizmos.color = Color.cyan; Gizmos.DrawLine(transform.position, sortingPoint); } }
Trees are tall... Their pivot point is at the base, but I need sorting based on where the trunk meets the ground, not the sprite's center. The yOffset
lets me adjust this per object. Now the player walks behind trees properly when they're above them, and in front when below.
Small Touch: Added debug gizmos that show exactly where each sprite is sorting from. Makes it much easier to tweak the offsets visually in the Scene view.
Now I can place trees, rocks, and furniture without worrying about weird rendering issues. hopefully.. lol.. Tomorrow: connecting the Crumble spell to actually affect the ground tiles! Yes I was supposed to do that today but I got distracted.
Did you like this post? Tell us
Leave a comment
Log in with your itch.io account to leave a comment.