Hello,
I am creating a 3D platformer and have created a character controller that allows the player to run and jump. The problem is when the player jumps all forward momentum is lost, the character just jumps straight vertically. I’m trying to have the player continue his/her forward momentum when jumping, and also allow them to control the character while in the air as that’s a common/expected mechanic.
I’ve read several posts on Unity and Stack Overflow and can’t find any similar questions/solutions. Can anyone help point out how I can accomplish this?
My code is almost all from Brackey’s 3D movement tutorial with a few small customizations and animation code: (Link to his tutorial: THIRD PERSON MOVEMENT in Unity - YouTube).
While I understand how the existing code works (after many hours reading about Eulers and Quaternions), unfortunately I can’t figure out how to both keep forward momentum while jumping and allow the player to control their position while in the air. Here is the code:
public class MovePlayer : MonoBehaviour
{
CharacterController controller;
Animator anim;
public Transform cam;
public float moveSpeed = 5.0f;
public float jumpHeight = 2f;
public float gravity = 18.0f;
public bool groundedPlayer;
public Vector3 jumpVector = Vector3.zero;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Awake()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
groundedPlayer = controller.isGrounded;
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 moveDirection = new Vector3(x, 0f, z).normalized;
if (moveDirection.magnitude >= 0.1f && groundedPlayer)
{
anim.SetBool("Moving", true);
float targetAngle = Mathf.Atan2(moveDirection.x, moveDirection.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * moveSpeed * Time.deltaTime);
if (Input.GetButtonDown("Jump"))
{
jumpVector.y = Mathf.Sqrt(jumpHeight * 2f * gravity);
}
}
else
{
anim.SetBool("Moving", false);
}
jumpVector.y -= gravity * Time.deltaTime;
controller.Move(jumpVector * Time.deltaTime);
}
}
Thank you in advance for any help you can offer.