I'm in Unity and I Wrote a Combat Script and It Works ... Kinda, Because If I Set the startTimeBtwAttack float to Any Higher 0 It Stops Working, Yes I Know My Script very very Long but if You Have Patience and Kindness Then Please Help Me, Here's The Code.
using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class PlayerCombat : MonoBehaviour { private PlayerMovement speed;
public bool hasSword = true;
private float timeBtwAttack;
public float startTimeBtwAttack;
public Animator animator;
public Transform attackPos;
public float attackRange;
public LayerMask whatIsEnemies;
public int damage;
public AudioSource swordSrc;
public AudioClip swordClip;
public float startDazedTime;
private float dazedTime;
private float attackTime = .25f;
private float attackCounter = .25f;
private bool isAttacking;
void Start()
{
speed = FindObjectOfType<PlayerMovement>();
}
void Update()
{
if (hasSword == true)
{
if (dazedTime <= 0)
{
speed.MovementSpeed = 5f;
}else
{
speed.MovementSpeed = 0f;
dazedTime -= Time.deltaTime;
}
if (timeBtwAttack <= 0)
{
timeBtwAttack = startTimeBtwAttack;
if(isAttacking)
{
attackCounter -= Time.deltaTime;
if (attackCounter <= 0)
{
animator.SetBool("isAttacking", false);
isAttacking = false;
}
}
if (Input.GetKeyDown(KeyCode.X))
{
dazedTime = startDazedTime;
attackCounter = attackTime;
animator.SetBool("isAttacking", true);
swordSrc.PlayOneShot(swordClip);
isAttacking = true;
Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies);
for (int i = 0; i < enemiesToDamage.Length; i++)
{
enemiesToDamage[i].GetComponent<EnemyScript>().TakeDamage(damage);
}
}
}else
{
timeBtwAttack -= Time.deltaTime;
}
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackPos.position, attackRange);
}
}