// I belive it has to do with the raycasting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
private float speed = 12f;
public float walkSpeed;
public float sprintSpeed;
public float gravity = -18f;
public float jumpHeight = 3f;
public MovementState state;
public enum MovementState
{
walking,
sprinting,
air
}
[Header("Keybinds")]
public KeyCode sprintKey = KeyCode.LeftShift;
public KeyCode crouchKey = KeyCode.LeftControl;
[Header("Crouching")]
public float crouchSpeed;
public float crouchYScale;
private float startYScale;
[Header("Ground")]
public Transform groundCheck;
public float groundDistance = 0.2f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
velocity = AdjustVelocityToSlope(velocity);
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
StateHandler();
if (isGrounded && velocity.y < 0)
{
velocity.y += -0.1f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
// start crouch
if(Input.GetKeyDown(crouchKey))
{
transform.localScale = new Vector3(x = 1f, crouchYScale = 0.5f, z = 1f);
velocity.y = -8f;
jumpHeight = 1f;
}
// stop crouch
if(Input.GetKeyUp(crouchKey))
{
transform.localScale = new Vector3(x = 1f, crouchYScale = 1f, z = 1f);
velocity.y =0f;
jumpHeight = 2f;
}
// When to jump
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void StateHandler()
{
//Mode - Sprinting
if(isGrounded && Input.GetKey(sprintKey))
{
state = MovementState.sprinting;
speed = sprintSpeed;
}
//Mode - Walking
else if (isGrounded)
{
state = MovementState.walking;
speed = walkSpeed;
}
//Mode - Air
else
{
state = MovementState.air;
}
}
private Vector3 AdjustVelocityToSlope(Vector3 velocity)
{
var ray = new Ray(transform.position, Vector3.down);
if(Physics.Raycast(ray, out RaycastHit hitinfo, 0.2f))
{
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitinfo.normal);
var adjustedVelocity = slopeRotation * velocity;
if(adjustedVelocity.y < 0)
{
return adjustedVelocity;
}
}
return velocity;
}
}