PlayerMove.cs

Home   »   PlayerMove.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    
    [SerializeField] private string HorizontalInputName;
    [SerializeField] private string VerticalInputName;
    [SerializeField] private float movementSpeed;

    private CharacterController charController;

    [SerializeField] private AnimationCurve jumpFallOff;
    [SerializeField] private float jumpMultiplier;
    [SerializeField] private KeyCode jumpKey;

    private bool isJumping;

    private void Awake(){
        charController = GetComponent();
    }

    private void Update() {
        PlayerMovement();
    }

    private void PlayerMovement(){
        float horizInput = Input.GetAxis(HorizontalInputName) * movementSpeed;
        float vertInput = Input.GetAxis(VerticalInputName) * movementSpeed;

        Vector3 forwardmovement = transform.forward * vertInput;
        Vector3 rightMovement = transform.right * horizInput;

        charController.SimpleMove(forwardmovement + rightMovement);

        JumpInput();
        
    }

    private void JumpInput(){
        if(Input.GetKeyDown(jumpKey) && !isJumping){
            isJumping = true;
            StartCoroutine(JumpEvent());
        }
    }

    private IEnumerator JumpEvent(){
        float timeInAir = 0.0f;


        do{
            float jumpForce = jumpFallOff.Evaluate(timeInAir);
            charController.Move(Vector3.up * jumpForce * jumpMultiplier * Time.deltaTime);
            timeInAir += Time.deltaTime;
            yield return null;
        } while (!charController.isGrounded && charController.collisionFlags != CollisionFlags.Above);

        isJumping = false;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *