Hi there.
I’m fairly new to Unity, so I have decided to take the simple challenge of recreating Pong, the old video game. However, I’m having some trouble when I’m moving the platforms. I added a rigidbody2D so that I could add a velocity with a up-and-down key press. However, I don’t want it to be affected by gravity, so I set the Gravity Scale to 0. However, when I apply a velocity to it, it goes flying off the screen, because there is no gravity to stop it. Is there a way to make it stop moving once I let go of the key?
I apologize if this question is difficult to understand.
Rigidbody.velocity sets the velocity that the object will be moving at. Like real life, objects follow Newton’s first law, so they won’t stop moving if you leave them alone. Therefore, you will need to reset their velocities if you wish for them to stop moving.
The way to literally do what you ask is as follows:
if(Input.GetKeyUp("w")) // Get key up is called when the key in question (w) stops being held
{
rigidbody.velocity = Vector3.zero; //Vector3.zero is shorthand for new Vector3(0,0,0).
//It can be used for Vector2 as well.
}
Or, a better way would be to store the users up or down input as a variable in itself, and always multiply the objects y axis (up/down) velocity by that variable. A good way of doing this is by using Input.GetAxis(“Vertical”). This method returns a positive float (number) when the W key or Up arrow are being held, and a negative float (number) when the S key or Down Arrow are being held, and the value increases every frame. If you use Input.GetAxisRaw(“Vertical”) instead, the values are a nice, fixed 1 or -1.
float verticalMovement = Input.GetAxisRaw("Vertical");
float speed = 5;
rigidbody.velocity = Vector3.up * speed * verticalMovement;
//Vector3.up is shorthand for new Vector3(0,1,0), so the object will not move on the x (horizontal)
// z (forward) axis.
If you wish to add Horizontal movement, use GetAxis(“Horizontal”), and store both vertical and horizontal values in a Vector2 variable.