Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to switch sprite side left and right without changing local scale

I’m making a 2D game and I want my player when he is moving left and right based on the Input Key to switch the side of my player’s sprite.

The way I’m handling it so far which it works for now is by changing the local scale on the X-Axis like this:

void Update()
{
    if (Input.GetKeyDown(KeyCode.A))
    {
        transform.localScale = new Vector3(-1, 1, 1);
    }
    else if(Input.GetKeyDown(KeyCode.D))
    {
        transform.localScale = new Vector3(1, 1, 1);
    }
}

The default is for the player to face the right side but when he press the A button the player will look to the left side and when he press D it will look back to the right side.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far everything is good, but when I try to increase my player’s size when he collects a power up everything is messed up.

To increase the size I’m using the DOTween package which provides an easy way for scaling up an object like this:

transform.DOScale(new Vector3(2, 2, 2),1.5f);

After that I realise that messing with the scale it can become really messed up.
My question is there any better way to handle the sprite side switch?

>Solution :

Actually this is an easy solution.

I suppose that you are using a Sprite Renderer component for your player.
On this component there is an option Flip which is used to flip your sprite on 2 Axis (X,Y). You can use the X-Axis in order to flip your spite left and right.

Simple create a reference of your Sprite Renderer component in your above script and then use the flip property to change your sprite side.

Here is an example:

private SpriteRenderer spriteRenderer;

void Start()
{
    spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.A))
    {
        spriteRenderer.flipX = true;
    }
    else if(Input.GetKeyDown(KeyCode.D))
    {
        spriteRenderer.flipX = false;
    }
}

Now you can use your DOTween to scale your player.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading