- Home /
Flipping a 2D GameObject
I have this script to make a 2D sprite walk left to right but when he turns left, he won't flip. Can anyone help me make him flip when he turns left.
public float walkSpeed = 2.0f;
public float wallLeft = 0.0f;
public float wallRight = 5.0f;
float walkingDirection = 1.0f;
Vector3 walkAmount;
// Update is called once per frame
void Update () {
walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;
if (walkingDirection > 0.0f && transform.position.x >= wallRight)
walkingDirection = -1.0f;
else if (walkingDirection < 0.0f && transform.position.-x <= wallLeft)
walkingDirection = 1.0f;
transform.Translate(walkAmount);
}
}
Answer by robertbu · Oct 06, 2013 at 11:19 PM
A solution is to change the texture scale.
renderer.material.SetTextureScale ("_MainTex", Vector2(-1,1));
Switch the sign on the first parameter of the Vector2 to reverse the image.
You can also use a shader with culling turned off and just rotate the object:
transform.eulerAngles = Vector3(0.0, 180.0, 0.0);
If you don't turn off culling, the object will disappear.
If you are going to have a lot of these objects, and you are going to use a texture atlas, a good way to flip is to change the uv coordinates in the mesh.
Answer by Hoeloe · Oct 06, 2013 at 10:56 PM
Well, that would be because none of that code has actually told it to flip around. All you're working with here is transform.Translate, which is entirely to do with movement (translation is a mathematical term for moving something). What you need to do is to change the scale of the character. It's quite a simple logical step to consider that if a scale of 1 in a certain axis is facing one way, then a scale of -1 in that axis will create the mirror image. All you need to do is to find the correct axis (most likely the z or x axis) in transform.localScale, and multiply it by -1.
@Hoeloe - workable solution, but I believe this plays havoc when colliders are involved.
That depends how you do it. If your collider or plane is not symmetric, then changing the scale of the texture plane without the collider will break things, though you can always enclose these inside a parent GameObject for the purpose of changing the scale.
Your answer
![](https://koobas.hobune.stream/wayback/20220613115435im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Mac App Sandbox Adding Capabilities 0 Answers
Unity 4.5 No Height map Button? 1 Answer
Help Please i have a Error saying CSharp-firstpass.dll.mdb" is denied. 0 Answers
Builds won't run at all 3 Answers
How to do slowly rising bar? 1 Answer