Reputation: 21
I'm quite new to unity, and I used this code to move the character while D is held down and reset horizontal velocity to 0 to prevent sliding. It worked fine before I added the else if but now it won't move at all.
void Update()
{
if (Input.GetKey(KeyCode.D))
{
Rigidbody.velocity = new Vector2 (speed * Time.fixedDeltaTime, 0);
}
else if (Input.GetKeyUp(KeyCode.D))
{
Rigidbody.velocity = new Vector2 (0,0);
}
}
Upvotes: 0
Views: 230
Reputation: 67
Don't use velocity I would use position that removes sliding completely:
void Update()
{
if (Input.GetKey(KeyCode.D))
{
transform.position = new Vector3 (speed * Time.fixedDeltaTime + transform.position.x, transform.position.y,0);
}
else if (Input.GetKeyUp(KeyCode.D))
{
transform.velocity = new Vector3 (0,0,0);
}
}
Upvotes: 1
Reputation: 66
My first thought is that you seem to be using Rigidbody
when you should be using Rigidbody2D
. You didn't clarify what version of Unity you are using but it seems like it's the 2D one. Using the wrong Rigidbody class could cause all sorts of unexpected behavior.
If that doesn't solve it the next obvious thing would be debugging. If the problem only emerged with the if-else, I would first check if its condition is properly met. maybe your program has some problem with the GetKeyUp function. Just check the 'if' is true when it should be, and print a simple message whenever it's true.
If the problem isn't there then it must be with the Rigidbody.velocity = new Vector2 (0,0);
line. perhaps there is another code affecting the velocity at the same time. Maybe gravity is set to an unusual scale and setting the vertical velocity to 0 causes unexpected behavior.
I'm fairly certain doing all of this will 100% solve your problem.
I Hope I Helped, Goodluck(;
Upvotes: 0