Untitled
unknown
plain_text
10 months ago
3.4 kB
25
Indexable
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 8f;
[SerializeField] private float jumpForce = 50f;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private float xMinClamp = -41.5f;
[SerializeField] private float xMaxClamp = 47.1f;
[SerializeField] private float gravity = -20f;
[SerializeField] private float playerFallTimer = 0f;
private PlayerControls inputActions;
private Rigidbody rb;
private Vector3 velocity;
private Vector2 movement;
private bool isGrounded = true;
private void Awake()
{
inputActions = new PlayerControls();
inputActions.Player.Enable();
inputActions.Player.Jump.performed += Jump_performed;
inputActions.Player.Move.performed += Move_performed;
rb = GetComponent<Rigidbody>();
}
private void Move_performed(InputAction.CallbackContext obj)
{
movement = obj.ReadValue<Vector2>();
}
private void Jump_performed(InputAction.CallbackContext obj)
{
if(isGrounded)
{
velocity.y = jumpForce;
}
}
private bool IsGrounded()
{
Vector3 rayOrigin = transform.position;
float rayLength = 0.1f;
if (Physics.Raycast(rayOrigin, Vector3.down, out RaycastHit hit, rayLength, groundLayer))
{
return true;
}
return false;
}
private void ProcessMovement()
{
if (movement != Vector2.zero)
{
Vector3 currentPosition = rb.position;
Vector3 moveVector = new Vector3(movement.x, 0f, 0f);
Vector3 newPosition = currentPosition + moveVector * moveSpeed * Time.fixedDeltaTime;
//clamp player
newPosition.x = Mathf.Clamp(newPosition.x, xMinClamp, xMaxClamp);
rb.MovePosition(newPosition);
}
}
private void FixedUpdate()
{
ProcessMovement();
ApplyGravityAndVelocity();
}
private void Update()
{
// Ground Check
isGrounded = IsGrounded();
if(velocity.y < 0f && isGrounded)
{
velocity.y = 0f;
}
}
private float PlayerGravity()
{
if (isGrounded)
{
gravity = 0f;
}
else
{
playerFallTimer -= Time.fixedDeltaTime;
if(playerFallTimer < 0)
{
gravity = -20f;
}
playerFallTimer = 0f;
}
return gravity;
}
private void ApplyGravityAndVelocity()
{
if (!IsGrounded()) //make the player fall down
{
velocity.y += PlayerGravity() * Time.deltaTime;
transform.Translate(0, velocity.y * Time.fixedDeltaTime, 0);
}
else if (IsGrounded()) //make the player jump with force without gravity
{
transform.Translate(0, velocity.y * Time.fixedDeltaTime, 0);
}
}
private void OnDestroy()
{
inputActions.Player.Disable();
}
}
Editor is loading...
Leave a Comment