- Home /
How do I apply gravity, but only in the y-axis?
In Unity, the gravity feature located on a Rigidbody does indeed apply an acceleration in the y direction on an object, but for some reason it also applies air resistance. It's like it slows the object in the x and z directions. I was wondering if there was a way either through scripting or even just through some fines in the inspector that can help me get a rigid body to only be affected on the y axis.
As others have said, gravity operates on the y axis only. Implementing your own gravity system doesn't seem like a smart way to resolve this. I think whatever's going on here isn't what you think it is. A video or even just a diagram showing the trajectory the object is taking might help.
Answer by TommyEaves2002 · Dec 07, 2015 at 06:45 PM
In terms of scripting you could put this line of code in your update function:
rigidbody.addForce(new Vector3(0, gravity, 0));
Remember to make gravity a negative value ;) Also rigidbody needs to be a variable with the rigidbody you want to apply the force to as a value. If you don't know how to do this put this in your start function:
rigidbody = this.gameobject.GetComponent<Rigidbody3D>();
To add a little more detail, Unity's gravity vector only adds to an object's velocity in the direction it pushes. If your velocity is (5, 0, 0) and gravity pulls your object down for 10 seconds, that 5 on the X-axis will not be changed due to gravity alone.
Rigidbody drag or collision friction, on the other hand, are what will slow your object down. Drag is calculated as:
rigidbody.velocity *= $$anonymous$$athf.Clamp01(1.0f - (rigidbody.drag * Time.fixedDeltaTime));
This also happens to mean that if rigidbody.drag / Time.fixedDeltaTime >= 1
your object will stop all motion every frame.
I already have my drag set to 0 in the inspector, and yet, my object continues to fail to maintain its horizontal velocity. Any ideas?
Well, to throw a few more questions out there, then, do you have any scripts modifying velocity in any way? Is there ever any point when friction might become a factor due to contact with another object? Is there any odd chance that there's a mix-up between velocity and rotational velocity?
To be honest, I'm not entirely sure where the problem would lie in this case. I've put together trajectory prediction scripts with no faults in their accuracy (including factoring in drag), so I can only guess that the problem might be found in something overlooked.
Answer by Fanttum · Dec 07, 2015 at 09:02 PM
You can change global gravity settings Edit>ProjectSettings>Physics also knows as the Physics Manager.
You might also be thinking of Drag that is slowing down your Rigidbody. Make sure it is set to zero so it won't slow down. Also maybe see Friction?
I already have my drag set to 0 in the inspector, and yet, my object continues to fail to maintain its horizontal velocity. Any ideas?