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. Dismiss Notice

[SOLVED] Image2DAlphaMask help needed

Discussion in 'Project Tiny' started by Rupture13, Apr 2, 2019.

  1. Rupture13

    Rupture13

    Joined:
    Apr 12, 2016
    Posts:
    128
    I want to have the pixelAccurate Sprite2DRendererHitBox functionality enabled. The documentation says that in order to do that, I need to add the Image2DAlphaMask to the entity with the Image2D component (which is not the same entity that has the Sprite2DRenderer component) before loading the image:

    Sprite2DRendererHitBox2D documentation
    Image2DAlphaMask documenation

    I, however, have no idea how to intercept the loading and add this component.

    Any help? :)
     
  2. Rupture13

    Rupture13

    Joined:
    Apr 12, 2016
    Posts:
    128
    Okay so I've found a solution (not sure if it's the best or only one):

    Since I couldn't seem to intercept the loading of the Image2D, I manually made it reload with the Image2DLoadFromFile component and then set the Image2DAlphaMask component in the same frame. For the loader I used the serialized image asset from UT_ASSET in runtime.

    A code example of all this:
    Code (CSharp):
    1. this.world.forEach([ut.Entity, Scratcher, ut.Core2D.Sprite2DRenderer], (entity, scratcher, renderer) => {
    2.  
    3.     let trueSource = this.world.getComponentData(renderer.sprite, ut.Core2D.Sprite2D).image;
    4.     if (!this.world.hasComponent(trueSource, ut.Core2D.Image2DAlphaMask)) {
    5.  
    6.         let loader = this.world.getOrAddComponentData(trueSource, ut.Core2D.Image2DLoadFromFile);
    7.         loader.imageFile = UT_ASSETS[this.world.getComponentData(trueSource, ut.Core2D.Image2D).sourceName.substring(9)];
    8.         this.world.setComponentData(trueSource, loader);
    9.  
    10.         let alphaMask = this.world.getOrAddComponentData(trueSource, ut.Core2D.Image2DAlphaMask);
    11.         alphaMask.threshold = 0.5;
    12.         this.world.setComponentData(trueSource, alphaMask);
    13.     }
    14. });