- Home /
Script to flip a sprite over the x axis not working? C#, Unity2D
This script should work, right? Well, it doesn't, I get no errors and my sprite is not flipping across the x axis, facing the other direction. Could somebody point out what I did wrong?
using UnityEngine; using System.Collections;
public class LRmovement : MonoBehaviour {
public float speed = 1f;
public float JumpSpeed = 10f;
private bool onPlatform;
void Start () {
}
void Update () {
if (Input.GetKey (KeyCode.D) && (transform.position.x < 1.5))
transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
transform.localScale = new Vector3 (-1f, 1f, 1f);
if (Input.GetKey (KeyCode.A) && (transform.position.x > -1.5))
transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
transform.localScale = new Vector3 (1f, 1f, 1f);
}
}
Answer by Cherno · Jul 19, 2015 at 08:08 PM
Took me a few minutes to figure it out, but it's actually pretty simple :D
You use no braces (was: parenthesis) with your if statements: That is fine as long as you remember that in this case, only the next line will be affected by that if statement; All further lines are called as usual, which, in the case of Update(), is every frame. So what happens is that the localScale is set to 1,1,1 every frame, no matter which keys your are pressing or whatever conditions should apply. The fix is of course simple: Just encapsulate the relevant lines.
if (Input.GetKey (KeyCode.D) && (transform.position.x < 1.5)) {//<- ding!
transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
transform.localScale = new Vector3 (-1f, 1f, 1f);
}//<- ding!
if (Input.GetKey (KeyCode.A) && (transform.position.x > -1.5)) {//<- ding!
transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
transform.localScale = new Vector3 (1f, 1f, 1f);
}//<- ding!
Best of luck with your project.
Braces. Parentheses are these: ( ). Brackets are these: [ ]. And braces: { }. A$$anonymous$$A "the squiggly things".
Ah, good to know. English is not my first language but now I at least know what I'm talking about :) Thanks for the clarification.
Thank you so much! That's so funny because all throughout my project I use brackets for my if statements, just here I forgot! Thanks!
Your answer
Follow this Question
Related Questions
My sprite is teleporting when I change my scale to -1 to flip it 1 Answer
Sprite flip movement script not working! HELP! 0 Answers
2D Box Collider doesn't flip with Sprite 3 Answers
LocalScale not working idealy 1 Answer
Flip Y Scale Value Issue 1 Answer