void FixedUpdate() { if (target != null && !attacking && !RunningThisRoutine(fleeing)) { Vector2 vectorToTarget = Vector2.zero; RaycastHit2D[] hits = new RaycastHit2D[raycastDepth]; Physics2D.RaycastNonAlloc(WC.transform.position, target.transform.position - transform.position, hits, aggroRange, collideLayerMask); string hitTag = null; bool hitIsTarget = false; foreach (RaycastHit2D hit in hits) { // go through hits from closest to farthest if (hit.collider != null && hit.fraction != 0) { hitTag = hit.collider.tag; vectorToTarget = hit.point - (Vector2)transform.position; // if the tag of this object is a target, then we will target this one since it is the closest foreach (string tag in targetTags) { if (tag == hitTag) { hitIsTarget = true; break; } } if (hitIsTarget) { break; } } } if (vectorToTarget != Vector2.zero) { if (vectorToTarget.magnitude < aggroRange) // if within aggro range { if (vectorToTarget.magnitude > attackRange || vectorToTarget.magnitude > tooFarThreshold) { Move(vectorToTarget); WC.AimInDirection(vectorToTarget); } else if (vectorToTarget.magnitude < tooCloseThreshold && hitIsTarget) { fleeing = MoveTo(vectorToTarget.normalized * -1 * Mathf.Abs(followDistance - vectorToTarget.magnitude)); WC.AimInDirection(-vectorToTarget); } else if (Time.time - lastAttackTime > attackCooldownLength && vectorToTarget.magnitude < attackRange && hitIsTarget) { if (WC.CanFire()) { StartCoroutine(ShootAttack(vectorToTarget, attackChargeTime, postAttackPauseDuration)); } } } } spriteDirection = vectorToTarget; } }
void FixedUpdate() { if (Time.time - lastAttackTime <= attackCooldownLength) { return; } // cancel if this enemy just attacked if (target != null && !attacking) // if the enemy is not attacking, do movement and try to attack { Vector2 vectorToTarget = Vector2.zero; RaycastHit2D[] hits = new RaycastHit2D[raycastDepth]; Physics2D.RaycastNonAlloc(WC.transform.position, target.transform.position - transform.position, hits, aggroRange, collideLayerMask); string hitTag = null; bool hitIsTarget = false; foreach (RaycastHit2D hit in hits) { // go through hits from closest to farthest if (hit.collider != null && hit.fraction != 0) { hitTag = hit.collider.tag; vectorToTarget = hit.point - (Vector2)transform.position; // if the tag of this object is a target, then we will target this one since it is the closest foreach (string tag in targetTags) { if (tag == hitTag) { hitIsTarget = true; break; } } if (hitIsTarget) { break; } } } if (vectorToTarget != Vector2.zero) { if (vectorToTarget.magnitude < aggroRange) // if within aggro range, move and aim weapon towards target { Move(vectorToTarget); WC.AimInDirection(vectorToTarget); } if (vectorToTarget.magnitude < attackRange && hitIsTarget && WC.CanFire()) // attack { StartCoroutine(SwordAttack(vectorToTarget, attackChargeTime, postAttackPauseDuration, postAttackRetreatDistance)); } } } }