- Home /
Simple rigidbody.AddForce only applying once each time key is pressed
Hello there.
I am making a very simple script that moves a character left when pushed left, and right when pushed right. The script below works fine, except that it only moves the character on the first frame that it is pushed. I want it to continue moving that direction the entire duration of the key being held down.
The following code is in the Update
function.
if (Input.GetKeyDown (KeyCode.LeftArrow)){
rigidbody.AddForce (Vector3.right * 100);
}
if (Input.GetKeyDown (KeyCode.RightArrow)){
rigidbody.AddForce (-Vector3.right * 100);
}
Thank you in advance.
Comment
Best Answer
Answer by Peter G · Oct 23, 2011 at 11:01 PM
You need to remove the "Down" from the GetKey.
if (Input.GetKey (KeyCode.LeftArrow)){
rigidbody.AddForce (Vector3.right * 100);
}
if (Input.GetKey (KeyCode.RightArrow)){
rigidbody.AddForce (-Vector3.right * 100);
}
GetKeyDown()
only returns true on the first frame that a key is pressed, and GetKey()
returns true every frame that the key is held down for.