Problem with IF-statement
I'm just starting to learn coding in unity. Playing around with the transform.position inside IF-statement. I want to make a cube start to move right or left depending on keyboard arrow input. And also make it stop moving when you press the arrow button again. Problem explained below the code:
void Update () { // PRESS RIGHT ARROW --> MOVE RIGHT if(Input.GetKeyDown(KeyCode.RightArrow) && movingleft==false && movingright==false) { movingright = true; movingleft = false; } // PRESS RIGHT ARROW WHEN MOVING RIGHT --> STOP MOVING if(Input.GetKeyDown(KeyCode.RightArrow) && movingright==true) { movingright = false; movingleft = false; } if(movingright==true) { transform.Translate(new Vector3(1,0,0) * Time.deltaTime); }
The bool moveright does never get to true, I think because the instant when you press the right arrow, the second if-statement gets true as well, since you're still holding the right arrow key for a bit. Without the second IF-statement, the code works and moveright becomes true.
Anybody any ideas? I will keep on working on this and will post it when I find it myself. :)
Answer by DimensionU · Jan 15, 2016 at 04:43 PM
I made a mistake initially in that the transform stuff should be outside of the key checks.
I see a couple of issues. One is as you described, the second test is overriding the first. But even if you eliminate the second test (within this frame), the key could still be down in a subsequent frame. For that reason, I'd test against GetKeyUp instead of GetKeyDown.
Here's how I'd approach it. BTW, this code isn't tested, but it should be sound.
void Update ()
{
if (Input.GetKeyUp(KeyCode.RightArrow))
{
movingright = !movingright;
movingleft = false;
}
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
movingleft = !movingleft;
movingright = false;
}
if (movingright) transform.Translate(new Vector3(1,0,0) * Time.deltaTime);
if (movingleft) transform.Translate(new Vector3(-1, 0, 0) * Time.deltaTime);
}
Answer by collinrijnvis · Jan 15, 2016 at 09:37 PM
Thank you!
movingright = !movingright
did the trick:
if(Input.GetKeyDown(KeyCode.RightArrow)) { movingright = !movingright; movingleft = false; } if(Input.GetKeyDown(KeyCode.LeftArrow)) { movingleft = !movingleft; movingright = false; } if(movingright==true) { transform.Translate(new Vector3(1,0,0) * Time.deltaTime); } else if(movingleft==true) { transform.Translate(new Vector3(-1,0,0) * Time.deltaTime); };
Now the values of movingleft and movingright are alternating with every keypress
Your answer
![](https://koobas.hobune.stream/wayback/20220612060325im_/https://answers.unity.com/themes/thub/images/avi.jpg)