- Home /
The question is answered, right answer was accepted
How to change and change back gravity?
I'm very new to coding and unity2d as a whole. I am trying to make my character glide if the player is holding down space by lowering the gravity. So how would I change the gravity back after lowering it? Thanks!
public class Glide : MonoBehaviour { private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.gravityScale = 2;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.gravityScale = 1;
} else if (rb.gravityScale != 2);
{
rb.gravityScale = 2;
}
}
}
Answer by Happy-Zomby · Sep 26, 2020 at 10:47 AM
Hi, I think you may want to use a Input.GetKeyUp(KeyCode.Space)) https://docs.unity3d.com/ScriptReference/Input.GetKeyUp.html in place of the "else if" Then I don't work with rigidbodies so not sure for the gravity scale. But the key up should help. Hope that helps
Or you can change if (Input.GetKeyDown(KeyCode.Space)) to Input.GetKey and use your else if (https://docs.unity3d.com/ScriptReference/Input.GetKey.html) but the previous method I mentioned may be more efficient.
Thanks so much, didn't know GetKeyUp was a thing! Worked Perfectly!
Follow this Question
Related Questions
How to reset the Gravity of an object from script 1 Answer
How can you make gravity to not have any acceleration but with const velocity? 1 Answer
Initial force in a rigidbody2d object? 1 Answer
How to instantly accelerate a falling game object to the maximum fall speed? 2 Answers
why unity official course use Time.deltaTime inside FixedUpdate 2 Answers