Beispiel #1
0
    /// <summary>
    /// Checks if there is a non transparent pixel in a renderer in this transform under the mouse. If
    /// the transform has a TilemapRenderer, simply returns that renderer.
    /// </summary>
    /// <param name="transform">transform to check</param>
    /// <param name="recentTouches">Dictionary from touch position to the pixel color and time the touch occurred,
    /// will be updated with the hit information if a hit occurs.</param>
    /// <returns>spriterenderer that was hit if there is a hit, or tilemaprenderer if transform has one</returns>
    public static Renderer IsPixelHit(Transform transform,
                                      Dictionary <Vector2, Tuple <Color, float> > recentTouches = null)
    {
        var tilemapRenderer = transform.gameObject.GetComponent <TilemapRenderer>();

        if (tilemapRenderer != null)
        {
            return(tilemapRenderer);
        }

        SpriteRenderer[] spriteRenderers = transform.GetComponentsInChildren <SpriteRenderer>(false);

        //check order in layer for what should be triggered first
        //each item ontop of a table should have a higher order in layer
        SpriteRenderer[] bySortingOrder =
            spriteRenderers.OrderByDescending(sRenderer => sRenderer.sortingOrder).ToArray();

        for (var i = 0; i < bySortingOrder.Length; i++)
        {
            SpriteRenderer spriteRenderer = bySortingOrder[i];
            Sprite         sprite         = spriteRenderer.sprite;

            if (spriteRenderer.enabled && sprite && spriteRenderer.color.a > 0)
            {
                MouseUtils.GetSpritePixelColorUnderMousePointer(spriteRenderer, out Color pixelColor);

                if (pixelColor.a > 0)
                {
                    var mousePos = Camera.main.ScreenToWorldPoint(CommonInput.mousePosition);
                    if (recentTouches != null)
                    {
                        if (recentTouches.ContainsKey(mousePos))
                        {
                            recentTouches.Remove(mousePos);
                        }

                        recentTouches.Add(mousePos, new Tuple <Color, float>(pixelColor, Time.time));
                    }

                    return(spriteRenderer);
                }
            }
        }

        return(null);
    }