How to flip my characters direction while running, jumping etc. 2D

So pressing the “D” key my character runs to the right just fine but I want to make it so when you press the “A” key the character flips and then continues to to run and jump to the left.

if (GetComponent().velocity.x > 0)

``````        transform.localScale = new Vector3(1f, 1f, 1f);

else if (GetComponent<Rigidbody2D>().velocity.x < 0)

transform.localScale = new Vector3(-1f, 1f, 1f);
``````

This little bit of code allows my character to flip left yes but whenever you move it at all he grows twice in size. It’s kind of funny but, not totally what I’m going for. I realize this may just be a silly mistake but, anyone that can help out would be much appreciated! Thank you all in advance

What is your initial size? Vector3(0.5f, 0.5f, 0.5f)?

You can probably use this:

private

``````Rigidbody myRigidbody;

void Start() {
myRigidbody = GetComponent<Rigidbody>();
}

void Update() {
if (myRigidbody.velocity.x != 0 && Mathf.Sign(myRigidbody.velocity.x) != Mathf.Sign(transform.localScale.x)) {
Vector3 localScale = transform.localScale;
localScale.x = Mathf.Sign(myRigidbody.velocity.x) * Mathf.Abs(localScale.x);
transform.localScale = localScale;
}
}
``````

You might find this tidier:

``````Rigidbody2D rigidbody;
SpriteRenderer sprite;

void Awake() {
rigidbody = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
}

void Update() {
if (!Mathf.Approximately(rigidbody.velocity.x, 0f))
sprite.flipX = rigidbody.velocity.x < 0f;
}
``````