- Home /
Keyboard Input + Camera Movement
I've written a script to move the camera based on keyboard input, which I pieced together from several parts of the Roll a Ball tutorial. However, when I release the key, it takes a fraction of a second for the movement to stop. Obviously, that's not optimal.
void Update ()
{
float horizontal = Input.GetAxis ("Pan Horizontal");
float vertical = Input.GetAxis ("Pan Vertical");
float zoom = Input.GetAxis ("Zoom");
Vector3 position = transform.position;
if (horizontal < 0) position.x += .1f;
if (horizontal > 0) position.x -= .1f;
if (vertical < 0) position.z += .1f;
if (vertical > 0) position.z -= .1f;
if (zoom < 0) position.y += .5f;
if (zoom > 0) position.y -= .5f;
transform.position = position;
}
Looking online, it seems there are MANY different ways to do this, but most of the examples I've seen have Time.deltaTime somewhere in the math. I thought adding this would fix the problem, but it only seems to have slowed down the movement rather than fix the input.
if (horizontal < 0) position.x += 10f * Time.deltaTime;
I could easily copy/paste someone else's script, but I'd prefer to understand what's wrong with my script and what parts need to change, rather than simply shove something in without educating myself.
Duplicate question of http://answers.unity3d.com/questions/1345066/input-camera-movement.html
Answer by Chris_Payne_QS · Apr 28, 2017 at 08:51 AM
Time.deltaTime is necessary to make the code adapt to different framerates - the Update function is called once per frame, but the number of frames completed per second can vary. Using your current code you could move the camera at 10 units per second at 100fps, but only 5 units per second at 50fps.
Your fix for that is correct - multiplying the desired speed by the deltaTime (time elapsed since last frame) - but it may feel slower if your game is running at >100 fps.
Regarding the time delay...I suspect deadzoning. Your camera will only stop moving when the input axes return to exactly zero. Unity's keyboard->axis mapping might have smoothing in it so it takes time to return to 0? A gamepad would not have any smoothing, but analogue sticks (being analogue) are notoriously bad at recentering. Most games define a "deadzone" area in the middle of the axis that is considered "fully upright", like this:
float DEADZONE = 0.1f;
if (horizontal < -DEADZONE) position.x += .1f;
if (horizontal > DEADZONE) position.x -= .1f;
This means the stick doesn't have to be EXACTLY upright to be considered "released".
Your answer

Follow this Question
Related Questions
2D Character Control Help 0 Answers
Input + Camera Movement 1 Answer
How do you make a method that gets called when a button gets highlighted using the arrow keys? 0 Answers
How come GUI window are not close according 1 Answer
SImple 3rd person camera that rotates towards movement direction 1 Answer