How to flip 2D object, mine isnt working nor any others i can find.
this is the program
if (Input.GetKeyDown (KeyCode.A)) { GetComponent()transform.localScale.x = -14; }
Error expecting ';' Error Unexpected sumbol '.' expecting ')',',',';','[', or '='
anyone know what I'm doing wrong?
Swagathaur has the answer for what you want to do, but to clarify on why you're getting the error, this is how GetComponent would work in this situation:
GetComponent().localScale.x
Transforms are already given a quick access variable though, as Swagathaur shows just use the variable 'transform'.
Answer by Swagathaur · Nov 01, 2015 at 10:57 PM
No big deal, you are just using GetComponent() a bit wrong. If you need to use GetComponent there are a few ways to do it, but by the looks of things you shouldnt need to, simply use:
if (Input.GetKeyDown (KeyCode.A)) { transform.localScale.x = -14; }
or better yet
if (Input.GetKeyDown (KeyCode.A)) { transform.localScale.x = -transform.localScale.x; }
The second code sample would cause the object to flip every time the user pressed A, even if they are already facing left. You need to add a direction check if you want to use that.
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.A)) { transform.localScale = -7, 7, 0 } would that make them only flip If they were facing the direction they are intended to flip too?
The first code sample that Swagathaur posted would work. The only issue is it would be trying to set the scale even if it's already set. Not sure how much overhead that would cause since it's not actually changing every time. Personally though, I'd do something like this:
bool facingRight = true;
float scaleNormal = 14f;//Easier to change later if needed
void Update()
{
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.A) && facingRight)
{
facingRight = false;
transform.localScale.x = -scaleNormal;
}else if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.D) && !facingRight)
{
facingRight = true;
transform.localScale.x = scaleNormal;
}
}
Swagathaur, that code seems to work. but it says I need getcomponent in a error, for some reason I have always ALWAYS needed getcomponent for things to work. know why?
What is the exact error you're getting? Also if you could copy/paste the lines you're using, as little details can sometimes matter.
Wouldn't let me reply directly to the comment with the code, but this'll work.
I see what's wrong now. I forgot that you can't directly modify one part of the scale. This same thing happens when trying to change any multipart variable on a component, like colors, rotations, etc. Just need to do it this way:
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.A)) {
Vector3 tempScale = transform.localScale;
tempScale.x = -14;
transform.localScale = tempScale;
}
Sorry, should have done it this way from the start, but I keep forgetting until I see the error. :)
Thanks soooo much! it worked perfectly. plus I learnt a lot!
Your answer
