Problem with my gravity code

So I looked up a function(?) for how to alter which way gravity pulls an object.
I’m using this code in C#

void Update () {
Physics.gravity = new Vector3(-1.0F, 0.0F, 0.0F);
}

The problem is that while it is indeed falling towards the -x axis, it is also still falling slightly along the y axis.

Thoughts?

The code tags are [code ][/code ], it isn’t HTML so it doesn’t use the pointy ones.

My guess is that this is caused by you placing this change in the Update code- there’s two reasons why this is bad. First, because it’s changing the gravity every-single-frame (that’s what Update does, it runs every frame), and gravity’s not going to change without you telling to change, so your new assignment will “stick” as long as it needs to. Put it in Awake() or Start() instead, if you must put it somewhere.

The second reason why Update is bad is that it doesn’t actually run until everything’s already been created- it doesn’t run during creation, it runs after creation, which means that when your object is created, it has gravity pointing the default way (down). The force lasts only until the first frame update, but it’s enough to give a character a slight “starting momentum” in that direction. Placing the change in Start() may fix that- putting it in Awake() almost certainly will, but the best bet is to change it in the global settings in your project in Edit → Project Settings → Physics.

1 Like

Oh, Duh that makes sense. Also sorry about the wrong code tags, I’ll keep that in mind for future posts. Thanks for your help.