// Update is called once per frame void Update () { FindTarget (); if (Target != null) { if (intendedAttack == null) { intendedAttack = ChooseAttack (); } float sqrDistanceToTarget = (Target.transform.position - transform.position).sqrMagnitude; float sqrRange = intendedAttack.range * intendedAttack.range; bool targetInRange = sqrDistanceToTarget < sqrRange; bool targetInSight = enemy.IsTargetVisible (Target, sightDistance); if (!targetInSight) { enemy.MoveDirection = enemy.lastSeenTargetPosition - transform.position; } else if (!targetInRange && !isAttacking) { // Approach target until in range enemy.MoveDirection = Target.transform.position - transform.position; } else { // Stop moving enemy.MoveDirection = Vector3.zero; // Begin or end a running attack if (!isAttacking && attackCooldown.IsTimeUp ()) { StartAttack (intendedAttack); intendedAttack = null; } else if (isAttacking && attackTime.IsTimeUp ()) { if (enemy.currentAttack.IsRanged ()) { FireProjectileWeapon (enemy.currentAttack); } EndAttack (); } // Wait for cooldown } // Always face the target, ignoring y coordinates if (!isAttacking || (isAttacking && enemy.currentAttack.IsRanged ())) { enemy.FaceDirection = Target.transform.position - transform.position; enemy.FaceDirection.y = 0; } } }
// Update is called once per frame void Update() { if (Target == null) { FindTarget(); } if (Target != null) { Vector3 directionToTarget = (Target.transform.position - transform.position); float sqrDistanceToTarget = directionToTarget.sqrMagnitude; directionToTarget.Normalize(); // Check if we should start an attack float ATTACK_RANGE_SQUARED = 16.0f; bool isInAttackRange = sqrDistanceToTarget <= ATTACK_RANGE_SQUARED; if (isInAttackRange && attackCooldown.IsTimeUp()) { enemy.WantsToAttack = true; attackCooldown.StartTimer(WAIT_TIME); } if (isInAttackRange && !enemy.isAttacking) { // Stop moving enemy.MoveDirection = Vector3.zero; } else { // Approach target until in range. Also approach during attack enemy.MoveDirection = directionToTarget; } // Always face and move towards the target enemy.FaceDirection = directionToTarget; } }