1
votes

I'm really new to using unity and C# so excuse me if this is a dumb question but I really haven't been able to figure it out..

I just want to flip my sprite in my 2D game but when I do that using localScale the location of the sprite changes too.

It's like this:

flipped right: | [sprite facing right]

flipped left: [sprite facing left] |

the "|" sign stays in one location in the game. Wow this is so hard to describe without pictures but I hope you can understand me. I can't post images because I'm new to the forum.

So the issue is: When I change the localScale the whole sprite moves and I don't understand why. Could someone please help me? Thanks in advance!

My code:

    private void HandleInput()
{
    if (Input.GetKey(KeyCode.D))
    {
        _normalizedHorizontalSpeed = 1;
        if (!_isFacingRight)
            Flip();
    }
    else if (Input.GetKey(KeyCode.A))
    {
        _normalizedHorizontalSpeed = -1;
        if (_isFacingRight)
            Flip();
    }
    else
    {
        _normalizedHorizontalSpeed = 0;
    }

    if(_controller.CanJump && Input.GetKeyDown(KeyCode.Space))
    {
        _controller.Jump();
    }
}
    private void Flip()
    {
        transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        _isFacingRight = transform.localScale.x > 0;
    }

}

1
Sorry this is not a duplicate. I have tried that code but the sprite moves for some reason instead of just flipping. I want the sprite to flip and stay put. So hard to explain without pictures. - mxmmix
Are you sure this component is attached to the sprite itself and not to the parent GameObject? - Max Yankov

1 Answers

3
votes

Make sure the origin of your sprite is configured correctly. In most cases, the origin of the sprite should be in the very middle, which would make a negative transform flip it around the center. If however the origin is in a corner, that position stays the same at any scale, meaning it'll be in the same place and your sprite will appear to move when flipping. This can also happen if your sprite only occupies a portion of the image used for the sprite - it's not actually moving, but since you can't see the rest of the image, it appears to be.