Trying to reduce gravity of player in unity2D

T33Rn

New member
Joined
Mar 24, 2021
Messages
1
Programming Experience
Beginner
Hi, I'm very new to C#, but I haven't found any information on the internet on how to do this, so I looked to a forum.
This is my script at the moment;



C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class useGlider : MonoBehaviour {
private Rigidbody2D rb;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}

void Update()
{
if(Input.GetKey(KeyCode.C))
{
rb.gravityScale *= 0.5f;
}
}



I'm trying to reduce the gravity by half as long as the "C" key is held down, but it isn't working. I realize that rb.gravityScale *= 0.5f might be multiplying the value instead? Is there any way to specifically set it to a number, because if I remove the * symbol the script becomes invalid. I would also like for gravity to revert back to normal as soon as the "C" key is no longer held.

Thanks.
 
Last edited by a moderator:
Solution
Well on the first call to your Update() method, you are halving the effect of gravity. But recall that your update method will get called multiple times per game loop. So the time it gets called, you'll be halving it again to bring it down to a quarter. And then the next call will halve it again.

One approach to handle this would be to have a bool that remembers if you've already halved gravity value. Set the bool to true the first time, and halve the value. When the button is not pressed anymore, double the value to restore gravity effects to normal, and clear the bool.
Well on the first call to your Update() method, you are halving the effect of gravity. But recall that your update method will get called multiple times per game loop. So the time it gets called, you'll be halving it again to bring it down to a quarter. And then the next call will halve it again.

One approach to handle this would be to have a bool that remembers if you've already halved gravity value. Set the bool to true the first time, and halve the value. When the button is not pressed anymore, double the value to restore gravity effects to normal, and clear the bool.
 
Solution
Back
Top Bottom