Question by
yasacan · Nov 14, 2019 at 12:45 PM ·
2d gamewaitforsecondstime.deltatimeif
Enemy waits 5 seconds after attack
I know this question asked before but I couldn't implement those answers to my code. My game is 2D game and I have flying enemies follow the player, when enemy closer than 6f it charges towards to player. On my code enemy keeps charging to player if player is closer than 6f. What I am trying to do is when enemy charges it should wait 5 seconds to charge again, but keep following the player, when 5 seconds passed if player is closer than 6f it charges again, could you help me where to implement time check?
Here is my code;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollow : MonoBehaviour
{
public float speed;
public float chargingSpeed;
private Transform target;
private Animator animator;
private bool isCharging;
private Vector3 positionToChargeTowards;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
animator = GetComponent<Animator>();
}
void FixedUpdate()
{
if (!isCharging)
{
if (Vector3.Distance(transform.position, target.position) > 6f)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
animator.SetBool("ChargeUp", false);
}
else if (Vector3.Distance(transform.position, target.position) <= 6f)
{
positionToChargeTowards = target.position;
isCharging = true;
}
if (transform.position.x < target.position.x)
{
transform.localRotation = Quaternion.Euler(0, 180, 0);
}
else
{
transform.localRotation = Quaternion.Euler(0, 0, 0);
}
}
else
{
animator.SetBool("ChargeUp", true);
Invoke("Charge",0.8f);
if (Vector3.Distance(transform.position, positionToChargeTowards) < 0.125f)
{
isCharging = false;
}
}
}
void Charge()
{
transform.position = Vector3.MoveTowards(transform.position, positionToChargeTowards, chargingSpeed * Time.deltaTime);
}
}
Comment