[英]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.只是想知道是否有办法在 Unity 中使用 C# 翻转游戏中的动画。 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.它应该将您的精灵(在 2d 游戏中)朝正确的方向翻转,并且附加到您角色的所有动画也会翻转。 I hope it helps.
我希望它有所帮助。
First of all, localScale is a Vector3, not a integer.首先,localScale 是 Vector3,而不是整数。
You can flip using scale
/ localScale
of the Transform
or the flipX
field of SpriteRenderer
.您可以使用
Transform
的scale
/ localScale
或 SpriteRenderer 的flipX
字段进行SpriteRenderer
。 To do this right you need to check your character's velocity in x-axis every frame and set the correct flip direction.要做到这一点,您需要每帧检查角色在 x 轴上的速度并设置正确的翻转方向。
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:示例代码(未测试),假设这是在您的根玩家游戏对象上,您的动画师也在此游戏对象或其子游戏对象上,并且您正在使用刚体 2D 移动它:
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.请注意,当水平V 在 -0.1 和 0.1 之间时,不会进行额外的翻转。 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.
此外,Unity Physics 太卡了,如果任何小的速度都会导致翻转,您的角色有时可能会抖动和来回翻转。 You should test this threshold value yourself to fit your need.
您应该自己测试此阈值以满足您的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.