- Home /
How to move a cube constantly with GetKeyDown
Hello! I need to be able to press "A" and the cube will keep moving to the left until it hits a wall. I've tried to do this by using Rigidbody.AddForce, but what happens is it isn't constant then, and I have to unlock the rotation constraints, which need to be locked so it has a smooth movement.
I recommend trying your solution before you tell me because it might not work. Thanks and please tell me fixes!
Answer by DreadKyller · Dec 21, 2017 at 01:01 AM
While the answer Konomira gave is correct, I feel a few more explanations should be added, specifically why in the sample in their answer they use GetKey
instead of GetKeyDown
.
GetKeyDown()
returns true only on the exact frame the key was pressed, and false until it's pressed again. GetKeyUp()
does the opposite, inform you when the key was released. If you wish to get whether the key is held down, you use GetKey()
Forces are used for many things, but imagine a force like an object hitting another object, or wind, etc, it applies a sudden force that changes the angular velocity and the velocity of the object based on its pivot and mass, applying a force constantly will accelerate the object. In your case you don't care about rotation and since you're getting key presses it's probably a character script. In this case just setting the velocity through rigidbody.velocity
is far more consistent.
Answer by Konomira · Dec 20, 2017 at 10:04 PM
This should move the object left, relative to its rotation.
void Update()
{
float speed = 1; // Adjust this as necessary
if(Input.GetKey(KeyCode.A)) // When 'A' is pressed
{
Vector3 v = -transform.right * speed; // -transform.right = left
GetComponent<Rigidbody>().velocity = v; // Sets velocity to left movement
}
}
This assumes you just want to tap the 'A' key. If you want it to be held down you could do else { GetComponent<RigidBody>().velocity = Vector3.zero;}
Your answer
![](https://koobas.hobune.stream/wayback/20220612144937im_/https://answers.unity.com/themes/thub/images/avi.jpg)