I have a simple question. Say I want to move my character by translating it with a Vector2 velocity varibale which is going to get it’s values from Input.GetAxis. When I write code as this:
Vector2 input=new Vector2(Input.GexAxis("Horizontal"), Input.GetAxis("Vertical"));
velocity.x=input.x* Time.deltaTime * moveSpeed
I get a weird error in which my character barely moves at all (it moves but very slowly and it stutters a lot). However, upon removing Time.deltaTime from velocity.x I get it to work normally. I know what Time.deltaTime is and what it is used for however I am not sure why I cannot use it with input.x but can use it with gravity?
btw moveSpeed and gravity are just float variables with publicly assigned values.
It’s because you’re multiplying by “Time.deltaTime” twice for your “velocity” value. You’re incorporating it on lines 2 and 3, and then again on line 4. The reason why this is making your character move slowly is because “Time.deltaTime” is going to be a small value (less than one); being as you’re accidentally applying it (multiplying by it) twice, your velocity value is going to end up being a lot smaller than it should be!
The solution is simple; remove “Time.deltaTime” from line 2 of your code. I’m guessing you need to keep it on line 3, as “gravity” is an acceleration, so you’ll want to multiply it by time to get the required change in velocity. Here’s the resulting code;
// Get the horizontal and vertical input.
Vector2 input = new Vector2(Input.GetAxis("Horizontal", Input.GetAxis("Vertical");
// Apply the horizontal input to the velocity.
velocity.x = input.x * moveSpeed;
// Apply gravity to the velocity (we need Time.deltaTime here, as gravity is an acceleration).
velocity.y += gravity * Time.deltaTime;
// Apply the resulting velocity to the character (multiply by Time.deltaTime to get the displacement).
transform.Translate(velocity * Time.deltaTime);