- Home /
Player movement change due to "if" statement?
I'm messing around with my player movement script and have noticed something which I cannot understand.
The original x-axis movement script (in FixedUpdate) I am using is:
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
With this, the player moves around and stops immediately when the button is no longer being pressed down. However, if I move the second line into an "if" statement (shown below), the player slides around like he's running on ice:
moveInput = Input.GetAxisRaw("Horizontal");
if (moveInput > 0.5 || moveInput < -0.5)
{
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
}
I'm curious why this is happening since both parts of the original script are intact, the only change that I can see is asking the perhaps redundant question of whether or not a button is being pressed down before letting the code run. I am very new to coding so I am expecting the answer to be something very simple, but I can't find any results on google. Thanks.
Answer by unity_jHVmmBKzAAXn6Q · May 31, 2019 at 05:19 AM
This piece of code should work perfectly!
moveInput = Input.GetAxisRaw("Horizontal");
if (moveInput > 0.5 || moveInput < -0.5){
rb.velocity = new Vector2(moveInput * 1, rb.velocity.y);
}else{
rb.velocity = Vector2.zero;
}
Explanation:
When you're not pressing the key down, the variable "moveInput" has a default value of 0, which makes translates into this: rb.velocity = new Vector2(0, rb.velocity.y);
making the object stop. But, when you use the if statement, the program never executes the previous statement, and that's similar to pushing an object on a surface where there is no friction (neither with the surface nor the air) it will simply keep moving forward.
Your answer
Follow this Question
Related Questions
how to move a gameobject only on the x axis? 1 Answer
Trying to make a 2d object launch towards the mouse when I left click. can anyone help? 2 Answers
3rd person camera bugs when moving backwards 0 Answers
How to move player head using mouse movement 0 Answers
rigidbody based character controller 0 Answers