Tap key to move object on y axis script

Hi,

How can i make an object move upwards a tiny amount every time i tap up arrow ? I want to put a rigid body on the object with gravity on it so that when the player doesn’t tap anymore, the object falls back down. I’m looking for scripting ideas in c# for this if possible.

Thanks :slight_smile:

“up arrow”… the key on the keyboard or a UI element on the screen?

the key on the keyboard :slight_smile:

Sounds like you need:

if(Input.GetKeyDown(KeyCode.UpArrow))
{
    GetComponent<Rigidbody>().AddRelativeForce(Vector3.up * someForceValue);
}

I’d play around with which ForceMode to use as the final parameter too, depending on your particular situation. If you want movement on taps-only, rather than being able to hold a button down, then the choice is between Impulse and VelocityChange- the difference being that the former factors in the object’s mass while the latter works on everything exactly the same way.

Edit: If you only ever want this object to be able to move up and down, be sure to constrain the X and Z positions in the Rigidbody settings. Forces are a little messy, and even if the only forces are ever in the +Y and -Y, from this function and gravity respectively, it’ll still push it around to the sides slightly just from floating point value shifts / tiny math adjustments and such, unless you specifically set constraints.

1 Like

Wonderful! Thank you very much for the info as well. For a noob like myself it really helps me understand more.