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

Time:11-11

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.

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?

CodePudding user response:

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.

CodePudding user response:

Why not do:

Vector3 localScale;
private boolIsFacingRight = true;
void Update()
{
    localScale = transform.localScale;
    if (Input.GetKeyDown(KeyCode.A))
    {
        localScale.x *= isFacingRight ? 1 : -1;
        isFacingRight = true;
        transform.localScale = localScale;
    }
    else if(Input.GetKeyDown(KeyCode.D))
    {
        localScale.x *= isFacingRight ? -1 : 1;
        isFacingRight = false;
        transform.localScale = localScale;
    }
}

That way you are only flipping your character on a single axis and you maintain the scaling versus setting it to a new vector 3 every time.

  • Related