Forum begins after the advertisement:


[Resource] Sorting your sprites in a top-down 2D game

Home Forums General Discussion [Resource] Sorting your sprites in a top-down 2D game

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #15935
    Terence
    Keymaster
    Helpful?
    Up
    0
    ::

    Hi folks, here is a Sortable script that you can use to easily sort your 2D sprites in your 2D game. We’ll be creating a video to address this issue very soon:

    using UnityEngine;
    
    /// <summary>
    /// This is a class that can be subclassed by any other class to make the sprites
    /// of the class automatically sort themselves by the y-axis.
    /// </summary>
    [RequireComponent(typeof(SpriteRenderer))]
    public abstract class Sortable : MonoBehaviour
    {
    
        SpriteRenderer sorted;
        public bool sortingActive = true; // Allows us to deactivate this on certain objects.
        public const float MIN_DISTANCE = 0.2f; // Minimum distance before the sorting value updates.
        int lastSortOrder = 0;
    
        // Start is called before the first frame update
        protected virtual void Start()
        {
            sorted = GetComponent<SpriteRenderer>();
        }
    
        // Update is called once per frame
        protected virtual void LateUpdate()
        {
            if (!sorted || !sortingActive) return;
            int newSortOrder = (int)(-transform.position.y / MIN_DISTANCE);
            if (lastSortOrder != newSortOrder) {
                lastSortOrder = sorted.sortingOrder;
                sorted.sortingOrder = newSortOrder;
            }
        }
    }
Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: