Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Mask/crop blank area around sprite. Shader?

Discussion in 'Scripting' started by Caliber, Jun 18, 2018.

  1. Caliber

    Caliber

    Joined:
    Feb 11, 2018
    Posts:
    85
    I recently purchased an asset that would save me a lot of coding. However there is one issue (that I didn't know before purchasing): the asset uses center of the sprite as a connection node. So for example on an item like a sword, the handle would be in the middle of the png image, and there is a lot of blank/transparent space around/below the actual sprite.

    This works fine when used precisely as in the asset example (player carrying/swinging the sword), but in my game it causes some issues. In inventory UI, the sword becomes tiny, and in world space all the blank space around the sword becomes clickable (when trying to pick up the sword from the ground).

    It seems like a shader would be the best solution. What I'm thinking about doing:
    Check pixel by pixel of the sprite for alpha values, to get the actual boundary of the sword, and then mask all the blank space. Then I could apply the shader as needed, and treat the sword sprite as any other sprite.

    I've never written any shaders, so before I spend a lot of time learning about them I'd like to know:
    • Can this be solved with shaders?
    • Is there some better way to solve it? (For UI, I could rescale the sprite and use UI Mask, but that only solves part of the issue)
    • Any examples of a shader with a similar functionality? It would be really helpful in getting me started.
     
  2. 1Piotrek1

    1Piotrek1

    Joined:
    Mar 14, 2014
    Posts:
    130
    There are a lot of things you can do in this situation and making a shader is in my opinion the most complicated one.
    1. Unity has Slice/Automatic option, that removes white space, also you can edit the pivot of each sprite in Sprite Editor.
    2. You can use external program to remove unnecessary space, it could be a plugin for some graphics editor (Gimp/Photoshop), a Python PIL script or something like this, just search for it. You can also use unity Texture2D class but opening and editing assets in unity is more complicated than just editing an image file.
     
    JoeStrout likes this.