Untitled
unknown
plain_text
8 months ago
4.0 kB
14
Indexable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
float playerHeight = 2f;
[SerializeField] Transform orientation;
[Header("Keybinds")]
[SerializeField] KeyCode jumpKey = KeyCode.Space;
[SerializeField] KeyCode sprintKey = KeyCode.LeftShift;
[Header("Jumping")]
public float jumpForce = 5f;
[Header("Drag")]
float groundDrag = 6f;
float airDrag = 0.1f;
[Header("Movement")]
private float moveSpeed = 6f;
float movementMultiplier = 10f;
public float walkSpeed;
public float sprintSpeed;
[SerializeField] float airMultiplier = 0.4f;
public MovementState state;
public enum MovementState
{
walking,
sprinting,
air,
}
float horizontalMovement;
float verticalMovement;
[Header("Ground Detection")]
[SerializeField] Transform groundCheck;
[SerializeField] LayerMask groundMask;
bool IsGrounded;
float groundDistance = 0.4f;
Vector3 moveDirection;
Vector3 slopeMovementDirection;
Rigidbody rb;
RaycastHit slopeHit;
private void StateHandler()
{
//sprinting
if(IsGrounded && Input.GetKey(sprintKey))
{
state = MovementState.sprinting;
moveSpeed = sprintSpeed;
}
//walking
else if (IsGrounded)
{
state = MovementState.walking;
moveSpeed = walkSpeed;
}
else
{
state = MovementState.air;
}
}
private bool OnSlope()
{
if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight / 2 + 0.4f))
{
if (slopeHit.normal != Vector3.up)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
private void Update()
{
IsGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
MyInput();
ControlDrag();
StateHandler();
if (Input.GetKeyDown(jumpKey) && IsGrounded)
{
Jump();
}
slopeMovementDirection = Vector3.ProjectOnPlane(moveDirection, slopeHit.normal);
}
void MyInput()
{
horizontalMovement = Input.GetAxisRaw("Horizontal");
verticalMovement = Input.GetAxisRaw("Vertical");
moveDirection = orientation.forward * verticalMovement + orientation.right * horizontalMovement;
}
void Jump()
{
if (IsGrounded)
{
rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
}
void ControlDrag()
{
if (IsGrounded)
{
rb.linearDamping = groundDrag;
}
else
{
rb.linearDamping = airDrag;
}
}
private void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
if (IsGrounded && !OnSlope())
{
rb.AddForce(moveDirection.normalized * moveSpeed * movementMultiplier, ForceMode.Acceleration);
}
else if (IsGrounded && OnSlope())
{
rb.AddForce(slopeMovementDirection.normalized * moveSpeed * movementMultiplier, ForceMode.Acceleration);
}
else if (!IsGrounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * movementMultiplier * airMultiplier, ForceMode.Acceleration);
}
}
}Editor is loading...
Leave a Comment