Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Changing the pivot of a sprite through code

Discussion in 'Project Tiny' started by ER_Dolleman, Dec 14, 2018.

  1. ER_Dolleman

    ER_Dolleman

    Joined:
    Dec 10, 2018
    Posts:
    19
    Is it possible to change the pivot of a sprite during runtime? I noticed that the Sprite2D component has a pivot property that can do that, but I don't know how to get a reference to the correct sprite.
     
  2. SoerenBachNielsen

    SoerenBachNielsen

    Joined:
    Dec 27, 2012
    Posts:
    38
    I haven't testet it, but couldn't you use something like this?


    this.world.usingComponentData(entitiyWithASprite, [ut.Core2D.Sprite2D], (sprite) => {
    sprite.pivot = new Vector2(1, 1);
    });
     
  3. ER_Dolleman

    ER_Dolleman

    Joined:
    Dec 10, 2018
    Posts:
    19
    It seems like the Sprite2D component is not attached to regular entities. They only have a Sprite2DRenderer.

    Code (JavaScript):
    1. this.world.forEach([ut.Core2D.Sprite2D], (sprite) => {
    2.            sprite.pivot = new Vector2(1, 1);
    3. });
    4.  
    This seems to work but it will change every pivot of every sprite. But if I filter for more components, the forEach will never execute.
     
  4. SoerenBachNielsen

    SoerenBachNielsen

    Joined:
    Dec 27, 2012
    Posts:
    38
    Hm, yea you're right. Just tried to make a quick example and even with a "Tag" component on one of the sprite renderer entities, if offsets both of them.
     
  5. ER_Dolleman

    ER_Dolleman

    Joined:
    Dec 10, 2018
    Posts:
    19
    Okay, from what I understand from it is there is an entity for every sprite. Components like Sprite2DRenderer have a reference to that entity.

    So, it is possible to get a specific Sprite2D component by doing this:
    Code (JavaScript):
    1. this.world.forEach([ut.Core2D.Sprite2DRenderer, game.PlayerTag], (renderer) => {
    2.  
    3.     let sprite = this.world.getComponentData(renderer.sprite, ut.Core2D.Sprite2D);
    4.  
    5.     sprite.pivot = new Vector2(1, 1);
    6.  
    7.     this.world.setComponentData(renderer.sprite, sprite);
    8. });
    This will change the pivot of every sprite with the PlayerTag. However, there is only 1 entity that contains the sprite, so any changes to it will apply to every Sprite2DRenderer that renders the same sprite whether it has the PlayerTag component or not.
    That's because Sprite2DRenderer.sprite is only a reference to the entity with that sprite, and multiple Sprite2DRenderers can use that same reference.

    Perhaps I can make a new entity and attach a sprite2D component to it with a different pivot.
     
    facundo_unity961 likes this.