Good day. I am having issues with trying to understand how i can build better jumping and gravity physics in my game… And please don’t suggest rigidbody
I have two scripts. One that in Update called to update the controller and then right after I update the motor of the controller.
// Update is called once per frame
public void Update()
{
motor.VerticalVelocity = motor.MoveVector.y;
motor.MoveVector = Vector3.zero;
//Apply any changes we need done to the Motor, then update them.
UpdateController();
motor.UpdateMotor();
//animator.Update();
}
Below is the player controller, this is where the jumping logic comes in.
private override void UpdateController()
{
bool isGrounded = this.GetComponent<CharacterController>().isGrounded;
//we check if isGrounded is true and we pressed Space button
if (isGrounded == true && Input.GetKey(KeyBindings.Jump))
{
isJumping = true;
base.motor.VerticalVelocity = minJumpForce;
}
if (isJumping && Input.GetKeyUp(KeyBindings.Jump))
isJumping = false;
if(isJumping && isGrounded == false && Input.GetKey(KeyBindings.Jump))
{
base.motor.VerticalVelocity += jumpForce;
if (base.motor.VerticalVelocity >= maxJumpForce)
{
base.motor.VerticalVelocity = maxJumpForce;
isJumping = false;
}
}
if (Input.GetKey(KeyBindings.Left) || Input.GetKey(KeyCode.LeftArrow))
base.motor.MoveVector += new Vector3(-1, 0, 0);
else if (Input.GetKey(KeyBindings.Right) || Input.GetKey(KeyCode.RightArrow))
base.motor.MoveVector += new Vector3(1, 0, 0);
Below we update the motor.
public void UpdateMotor()
{
// Transform MoveVector to World Space
MoveVector = transform.TransformDirection(MoveVector);
// Normalize our MoveVector if Magnitude is > 1
if (MoveVector.magnitude > 1)
MoveVector = Vector3.Normalize(MoveVector);
// Multiply MoveVector by MoveSpeed
MoveVector *= MoveSpeed;
// Reapply Verticle Velocity to MoveVector.y
MoveVector = new Vector3(MoveVector.x, VerticalVelocity, MoveVector.z);
// Apply Gravity
ApplyGravity();
// Move the Character in World Space
GetComponent<CharacterController>().Move((MoveVector * 5) * Time.deltaTime);
}
/// <summary>
/// Applies the gravity.
/// </summary>
private void ApplyGravity()
{
//Make sure we are not exceeding out -Terminal Velocity
if (MoveVector.y > -TerminalVelocity)
MoveVector = new Vector3(MoveVector.x, MoveVector.y - Gravity * Time.deltaTime, MoveVector.z);
if (GetComponent<CharacterController>().isGrounded && MoveVector.y < -1.0f)
MoveVector = new Vector3(MoveVector.x, -1.0f, MoveVector.z);
}
I would appreciate any help… The jumping doesn’t seem to be consistent If someone wants to talk in person, id love to talk out my issues and show more code.