- Home /
Gravity on object not working correctly
Hello Unity community,
I am having a slight issue with rigid body gravity. The gravity is set in the rigid body properties as default, when I am moving my character and jump in the air the character falls briefly then stops falling and continues moving forward until I let go of the controller at which point gravity kicks back in.
I think it has something to do with the change in forces I am applying to the character but I assumed that gravity being a constant would apply itself to the Y velocity.
Anyway here is my code for the movement and the jump
private Vector3 jumpVelocity = new Vector3 (0, 12, 0);
void move()
{
float maxVel = 30.0f;
if(leftThumbValueX > 0.01 || leftThumbValueX < -0.01 && isGrounded == true)
{
//applies a velocity change in the direction character is facing
if(leftThumbValueX < -0.01)
{
rigidbody.AddForce(transform.forward.normalized * (leftThumbValueX*=-1), ForceMode.VelocityChange);
}
else
{
rigidbody.AddForce(transform.forward.normalized * leftThumbValueX, ForceMode.VelocityChange);
}
//clamps Roybot to maximum velocity
if(velocity.z >= maxVel)
{
rigidbody.velocity = maxVelocity;
}
if(velocity.z <= -maxVel)
{
rigidbody.velocity = -maxVelocity;
}
}
//print(thumbValue);
print(rigidbody.velocity);
}
and here is the jump function:
void jump()
{
if(aButton > 0 && isGrounded)
{
rigidbody.AddForce(jumpVelocity, ForceMode.VelocityChange);
isGrounded = false;
}
}
Answer by AlucardJay · Apr 21, 2013 at 04:06 PM
Everytime you state rigidbody.velocity , you are directly modifying the velocity, so gravity is overwritten. So you have to factor in gravity before you hard code the velocity. This doesn't mean having to calculate it manually, simply use the current velocity.y somewhere in your calculations.
Vector3 calcVel = Vector3.zero;
//clamps Roybot to maximum velocity
if(velocity.z >= maxVel)
{
calcVel = maxVelocity;
calcVel.y += rigidbody.velocity.y;
rigidbody.velocity = calcVel;
}
if(velocity.z <= -maxVel)
{
calcVel = -maxVelocity;
calcVel.y += rigidbody.velocity.y;
rigidbody.velocity = calcVel;
}