Currently working on a character controller script and I’m trying to implement a jump but its seemingly not applying the forces. I’m fairly new to programming so I’m sure there’s something I’m not catching but here is where I’m at. The debug log does print the “Jumped” message but the player stays grounded. Any help/tips on writing this better appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField]
float walkSpeed = 5f;
[SerializeField]
float jumpForce = 10f;
[SerializeField]
float gravityValue = -9.81f;
[SerializeField]
float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
bool groundedPlayer;
Vector2 movementInput;
Vector3 playerVelocity;
Transform cameraMainTransform;
CharacterController controller;
[SerializeField]
InputActionReference walk, jump, interaction;
private void Start() {
controller = GetComponent<CharacterController>();
cameraMainTransform = Camera.main.transform;
}
private void Update() {
ApplyMovement();
ApplyJump();
GroundCheck();
}
void ApplyMovement(){
movementInput = walk.action.ReadValue<Vector2>();
Vector3 movementVector = new Vector3(movementInput.x, 0f, movementInput.y);
if(movementVector.magnitude >= 0.1f){
float targetAngle = Mathf.Atan2(movementVector.x, movementVector.z) * Mathf.Rad2Deg + cameraMainTransform.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 * Time.deltaTime * walkSpeed);
}
//playerVelocity.y += gravityValue * Time.deltaTime;
}
void ApplyJump(){
float jumpValue = jump.action.ReadValue<float>();
if(jump.action.triggered && groundedPlayer){
playerVelocity.y += Mathf.Sqrt(jumpForce * -1.0f * gravityValue);
Debug.Log("Jumped");
}
}
void GroundCheck(){
RaycastHit rayHit;
if(Physics.Raycast(transform.position, -transform.up, out rayHit, 0.1f)){
groundedPlayer = true;
}
else{
groundedPlayer = false;
}
}
}