using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed;
public float jumpForce;
public int extraJump = 1;
public Transform feet;//ground stuff
public float checkRadius;
public LayerMask groundLayer;
//private variables
private float leftrightInput;
private bool facingRight = true;
private bool isGrounded;
private bool isGrounded1;
private bool isAttacking;
private int jumpCount = 0;
private float jumpCoolDown;
private Animator anim;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
isGrounded = (Physics2D.OverlapCircle(feet.position, checkRadius, groundLayer));//creating a small circle beneath player character
CheckGrounded();
if (facingRight == false && leftrightInput > 0)
Flip();
else if (facingRight == true && leftrightInput < 0)
Flip();
//set animator parameters
anim.SetBool("run", leftrightInput != 0 && !isAttacking);
anim.SetBool("isJumping", !isGrounded);
HandleInputs();
EndAnim();
}
private void FixedUpdate()
{
leftrightInput = Input.GetAxis("Horizontal");//horizontal movement
rb.velocity = new Vector2(leftrightInput * movementSpeed, rb.velocity.y);
HandleAttack();
}
void Flip()//fliping the player
{
facingRight = !facingRight;
Vector2 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
void Jump()
{
if (isGrounded || jumpCount < extraJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount++;// double jump
}
}
void CheckGrounded()
{
if(isGrounded)// double jump mechanic
{
isGrounded1 = true;
jumpCount = 0;
jumpCoolDown = Time.time + 0.2f;
}
else if (Time.time < jumpCoolDown)
{
isGrounded1 = true;
}
else
{
isGrounded1 = false;
}
}
void HandleAttack()
{
if (isAttacking)
{
anim.SetTrigger("attack");
/*if (anim.GetCurrentAnimatorStateInfo(0).IsName("attack"))
{
movementSpeed = 0f;
}
else
{
movementSpeed = 7f;
}*/
}
}
void HandleInputs()
{
if(Input.GetKeyDown(KeyCode.E) && isGrounded)
{
isAttacking = true;
}
}
void EndAnim()
{
if (anim.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
isAttacking = false;
}
}