95 lines
2.0 KiB
C#
95 lines
2.0 KiB
C#
using UnityEngine;
|
|
|
|
public class Player : MonoBehaviour
|
|
{
|
|
private Animator anim;
|
|
private Rigidbody2D rb;
|
|
|
|
[Header("Movement details")]
|
|
[SerializeField] private float moveSpeed = 4.58f;
|
|
[SerializeField] private float jumpForce = 12;
|
|
private bool facingRight = true;
|
|
private float xInput;
|
|
|
|
[Header("Collision details")]
|
|
[SerializeField] private float groundCheckDistance;
|
|
[SerializeField] private LayerMask whatIsGround;
|
|
private bool isGrounded;
|
|
|
|
private void Awake()
|
|
{
|
|
rb = GetComponent<Rigidbody2D>();
|
|
anim = GetComponentInChildren<Animator>();
|
|
}
|
|
|
|
private void Update()
|
|
|
|
{
|
|
HandleCollision();
|
|
HandleInput();
|
|
HandleMovement();
|
|
HandleAnimations();
|
|
HandleFlip();
|
|
}
|
|
|
|
private void HandleInput()
|
|
{
|
|
xInput = Input.GetAxisRaw("Horizontal");
|
|
|
|
if (Input.GetKeyDown(KeyCode.K))
|
|
{
|
|
jump();
|
|
}
|
|
}
|
|
|
|
|
|
private void HandleAnimations()
|
|
{
|
|
bool isMoving = rb.linearVelocity.x != 0;
|
|
anim.SetBool("isMoving", isMoving);
|
|
}
|
|
|
|
private void HandleMovement()
|
|
{
|
|
rb.linearVelocity = new Vector2(xInput * moveSpeed, rb.linearVelocity.y);
|
|
}
|
|
|
|
private void jump()
|
|
{
|
|
if (isGrounded)
|
|
{
|
|
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
|
|
}
|
|
}
|
|
|
|
private void HandleCollision()
|
|
{
|
|
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, whatIsGround);
|
|
}
|
|
|
|
private void HandleFlip()
|
|
{
|
|
if(rb.linearVelocity.x > 0 && facingRight == false)
|
|
{
|
|
Flip();
|
|
}
|
|
else if (rb.linearVelocity.x < 0 && facingRight == true)
|
|
{
|
|
Flip();
|
|
}
|
|
}
|
|
|
|
private void Flip()
|
|
{
|
|
transform.Rotate(0, 180, 0);
|
|
facingRight = !facingRight;
|
|
}
|
|
|
|
private void OnDrawGizmos()
|
|
{
|
|
Gizmos.DrawLine(transform.position, transform.position + new Vector3(0, -groundCheckDistance));
|
|
}
|
|
|
|
|
|
}
|