简体   繁体   中英

How to flip a x-axis running animation in a game in Unity?

Just wondered if there was a way to flip an animation in a game using C# in Unity. Ive tried the following, to get my character to flip direction:

this.gameObject.transform.localScale =1

...
this.gameObject.transform.localScale =-1

but it doesn't seem to work.Any ideas?

If you want to flip your sprite in the direction he is walking, then you may try this.

 private void flipSprite()
{
    bool runningHorizntaly = Mathf.Abs(myRigidbody2D.velocity.x) > Mathf.Epsilon;

    if(runningHorizntaly)
    {
        transform.localScale = new Vector2(Mathf.Sign(myRigidbody2D.velocity.x), 1f);
    }
}

It should flip your sprite (in a 2d game) in the right direction, and all Animations attached to your character are also flipping. I hope it helps.

First of all, localScale is a Vector3, not a integer.

You can flip using scale / localScale of the Transform or the flipX field of SpriteRenderer . To do this right you need to check your character's velocity in x-axis every frame and set the correct flip direction.

Sample codes (not tested), assuming this is on your root player gameObject, your animator is also on this gameObject or its child gameObject, and you are moving it with rigidbody2D:

const float MIN_FLIP_THRESHOLD = 0.1f;
static readonly Vector3 FACE_RIGHT = Vector3.one;
static readonly Vector3 FACE_LEFT = new Vector3(-1, 1, 1);
Rigidbody2d rb;

void Awake() {
    rb = GetComponent<Rigidbody2D>();
}
void Update(){
    var horizontalV = rb.velocity.x;
    if (horizontalV > MIN_FLIP_THRESHOLD) {
        transform.localScale = FACE_RIGHT;
    } else if (horizontalV < -MIN_FLIP_THRESHOLD) {
        transform.localScale = FACE_LEFT;
    }
}

Notice that when horizontalV is within -0.1 and 0.1 no extra flipping is done. This is usually what you want as you don't want your flipping to be too sensitive. Moreover, Unity Physics is too jank and if any small velocity can cause a flip, your character likely will jitter and flip back and forth sometimes. You should test this threshold value yourself to fit your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM