How to change gravity in unity 3d
Asked Answered
S

4

0

Does anyone know how to change a rigidbody gravity with a press of a button, with a script, Does anyone have one i can borrow? ( as for people who are confused im trying to make an object change gravity or stick to a celing like flying up with a button not directy reverse the rigidbody gravity maybe by adding an opposing force) ( im not sure but i think u might be able to achive this with constant force) if u cant do it could u make it so the guy like flyes up the the cealing maybe even make him jump

Slime answered 29/11, 2023 at 9:49 Comment(0)
T
0

Doesn’t seems like you can toggle the gravity force on given rigidbody, only for all rigidbodies which is an overkill. So turn usegravity off for that body, and imitate it yourself, giving it an acceleration you want. Main gravity is accessed as Physics.gravity btw, in case that’s really what you want.

Tomlinson answered 29/11, 2023 at 9:38 Comment(0)
G
0

As said, you can’t set the gravity directly. What you can do though, is change the mass of the rigidbody, which then e.g. falls slower.

Gourmandise answered 29/11, 2023 at 9:42 Comment(0)
S
0

Could maybe u just make the guy fly upwards in a way

Slime answered 29/11, 2023 at 9:45 Comment(2)

Simply change the gravity to a negative number.

Gourmandise

Mass not gravity, sry

Gourmandise
T
0

So after you redacted this, I see you want to just add another acceleration. Remember that gravity is not a force as you expect, it’s an acceleration, it does not care about mass of the rigidbody (well only if it’s positive or negative). So, for moments you want your rigidbody to go up, add the opposing acceleration (with optionally turning off gravity on it), something like

bool isFlyingUp;
Vector3 fakeGravity = new Vector3(0, -20, 0);

void FixedUpdate()
{
    if(isFlyingUp){
        rigidbody.velocity += fakeGravity * Time.fixedDeltaTime;
    }
}

I hope I didn’t mess up with physics here much, not totally sure if I wrote code piece right.

Also I would likely turn gravity off while flyingup so it don’t fight with my force, like this

public Rigidbody body;
private bool _isFlyingUp;
public bool isFlyingUp{
    get { return _isFlyingUp;}
    set { body.useGravity = value; _isFlyingUp = value;}
}
Vector3 fakeGravity = new Vector3(0, -20, 0);

void FixedUpdate()
{
    if(isFlyingUp){
        body.velocity += fakeGravity * Time.fixedDeltaTime;
    }
}
Tomlinson answered 29/11, 2023 at 21:32 Comment(4)

Im sorto of new so how can you put this with a button

Slime

do we do the get key down or

Slime

Didnt realy work but it made him air jump

Slime

Toggle isFlyingUp on/off on getkeydown, yeah

Tomlinson

© 2022 - 2024 — McMap. All rights reserved.