using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hero : MonoBehaviour
{
[SerializeField] private float speed = 3f;
[SerializeField] private int lives = 3;
[SerializeField] private float jumpForce;
[SerializeField] GameObject AttackHitBox;
bool isGroundet = false;
bool isAttacing = false;
bool resDamage = true;
bool atackAktive = false;
[SerializeField]
Transform groundCheck;
private Rigidbody2D rb;
private SpriteRenderer sprite;
private Animator animator;
public int power = 1;
void Start()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponentInChildren<SpriteRenderer>();
animator = GetComponent<Animator>();
AttackHitBox.SetActive(false);
}
private void Run()
{
if (isGroundet == true)
{
if (isAttacing == false)
State = States.Run;
}
Vector3 dir = transform.right * Input.GetAxis("Horizontal");
transform.position = Vector3.MoveTowards(transform.position, transform.position + dir, speed * Time.deltaTime);
if (dir.x < 0.0f)
{
transform.localScale = new Vector3(1, 1, 1);
}
else
{
transform.localScale = new Vector3(-1, 1, 1);
}
}
private void Jump()
{
rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
}
private void Update()
{
if (isGroundet)
{
if (isAttacing == false)
State = States.Idle;
}
if (Input.GetButton("Horizontal"))
{
Run();
}
if (Input.GetButtonDown("Jump") && isGroundet == true)
{
Jump();
}
if (Input.GetButtonDown("Fire1"))
{
if (atackAktive == false)
{
State = States.Attack;
DoAttack();
}
}
}
private void FixedUpdate()
{
CheckGround();
}
private void CheckGround()
{
if (Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground")))
{
isGroundet = true;
}
else
{
isGroundet = false;
if (isAttacing == false)
State = States.Jump;
}
}
private void DoAttack()
{
if (isAttacing == false)
{
isAttacing = true;
StartCoroutine(DoAttacking());
StartCoroutine(AttakSpeed());
}
}
IEnumerator DoAttacking()
{
AttackHitBox.SetActive(true);
yield return new WaitForSeconds(0.3f);
AttackHitBox.SetActive(false);
isAttacing = false;
}
IEnumerator AttakSpeed()
{
atackAktive = true;
yield return new WaitForSeconds(1f);
atackAktive = false;
}
private States State
{
get { return (States)animator.GetInteger("State"); }
set { animator.SetInteger("State", (int)value); }
}
}
public enum State
{
Idle,
Run,
Jump,
Attack
}