SchoolFightingSimple/Assets/Scripts/PlayerMovement.cs

69 lines
1.7 KiB
C#
Raw Normal View History

2023-08-18 03:06:44 +02:00
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
public float maxSpeed = 10f;
public float jumpTime = 0.5f; // Maximum time the jump key can be held
public Transform groundCheck;
public LayerMask groundLayer;
private Rigidbody2D rb;
private bool isGrounded;
private bool isJumping;
private float jumpTimeCounter;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// Check if the player is grounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
// Movement
float moveDirection = Input.GetAxis("Horizontal");
Vector2 movement = new Vector2(moveDirection, 0f);
// Apply speed cap
if (Mathf.Abs(rb.velocity.x) > maxSpeed)
{
movement.x = 0f;
}
// Jumping
if (isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
if (Input.GetKey(KeyCode.Space) && isJumping)
{
if (jumpTimeCounter > 0)
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Force);
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
rb.AddForce(movement * moveSpeed, ForceMode2D.Force);
}
}