- Home /
Self answered.
How do add gravity?
I have gravity on my player but its not working Here is my code:
void Update ()
{
moveDirection.y -= falling.accelerationDueToGravity * falling.playerMass * Time.deltaTime;
moveDirection.y = Mathf.Max (velocity.y, -falling.terminalVelocity);
playerController.Move (moveDirection * Time.deltaTime);
}
Those variables are in classes, that's why i have things like falling.acceleration.
When I play, the gravity is not working, please help. Thanks in advance.
What is velocity.y, and are you sure you $$anonymous$$athf.max() call results in something else than 0? Time to debug your values with debugger or Debug.Log()
What's the value of movedirection after each frame ? Is it set properly ?
Answer by Fran-Martin · Feb 27, 2015 at 03:58 PM
If you want your object (e.g. a player) to fall due to gravity, you need to attach rigidbody and mesh components to the gameobject.
To change gravity's value through scripting Physics.gravity = Vector3(0, -9.8f, 0);
or go to Edit>Project Settings>Physics
http://docs.unity3d.com/ScriptReference/Physics-gravity.html
Answer by ScopedGames · Feb 27, 2015 at 05:19 PM
Hi sorry for wasting your time i made a stupid mistake. Thanks nonetheless for the help.
Here is the working code:
void Update ()
{
velocity = playerController.velocity;
moveDirection.y -= falling.accelerationDueToGravity * falling.playerMass * Time.deltaTime;
moveDirection.y = Mathf.Max (moveDirection.y, -falling.terminalVelocity);
playerController.Move (moveDirection * Time.deltaTime);
}