Untitled

 avatar
unknown
plain_text
3 years ago
2.8 kB
3
Indexable
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private Transform playercamera;
    [SerializeField] private float mouseSensitivity = 7f;
    [SerializeField] private float walkSpeed = 100f;
    [SerializeField] [Range(0.0f, 1.0f)] private float moveSmoothTime = 0.05f;
    [SerializeField] [Range(0.0f, 1.0f)] private float mouseSmoothTime = 0.003f;
    [SerializeField] private float gravityforce;
    private float gravity = 0;
    private bool isHitting = false;


    CharacterController characterController;

    Vector2 currentVelocity = Vector2.zero;
    Vector2 currentDirection = Vector2.zero;
    Vector2 currentMouseVelocity = Vector2.zero;
    Vector2 currentMouseDirection = Vector2.zero;



    private float cameraPitch = 0f;



    private void Awake()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;

    }
    // Update is called once per frame
    void Update()
    {
        GravityControl();
        Jump();
        MouseLook();
        InputDirection();

        isHitting = Physics.Raycast( playercamera.transform.position, playercamera.transform.forward);
     }

    private void GravityControl()
    {
        gravity -= gravityforce;
        characterController.Move(new Vector3(0, gravity, 0));
        if (characterController.isGrounded)
        {
            gravity = 0f;  
        }
    }

    private void Jump()
    {
        if (characterController.isGrounded && Input.GetButtonDown("Jump"))
        {
            Debug.Log("JUMPING");

            gravity += 0.1F;

        }
    }

    private void MouseLook()
    {

        Vector2 targetMouseAxis = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        currentMouseDirection = Vector2.SmoothDamp(currentMouseDirection, targetMouseAxis, ref currentMouseDirection, mouseSmoothTime);

        cameraPitch -= currentMouseDirection.y * mouseSensitivity;
        cameraPitch = Mathf.Clamp(cameraPitch, -90f, 90f);

        playercamera.localEulerAngles = Vector3.right * cameraPitch;

        transform.Rotate(Vector3.up * currentMouseDirection.x * mouseSensitivity);

    }

    private void InputDirection()
    {

        Vector2 targetDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        targetDirection.Normalize();

        currentDirection = Vector2.SmoothDamp(currentDirection, targetDirection, ref currentVelocity, moveSmoothTime);

        Vector3 velocity = (transform.forward * currentDirection.y + transform.right * currentDirection.x) * walkSpeed;

        characterController.Move(velocity * Time.deltaTime);



    }

    
}
Editor is loading...