// Update is called once per frame void Update() { GameObject closestAlly = null; float minDist = float.MaxValue; // find the closest ally foreach (GameObject ally in battle.Allies) { float dist = Vector3.Distance(transform.position, ally.transform.position); if (dist < minDist) { minDist = dist; closestAlly = ally; } } // move towards them movement.HandleMovement(closestAlly.transform.position, shootDist, false); gun.transform.LookAt(closestAlly.transform.position + new Vector3(0f, 2f, 0f)); // attack if close enough if (Vector3.Distance(closestAlly.transform.position, transform.position) <= shootDist) { if (shootCD <= 0.0f) { shoot.Shoot(); shootCD += shootTimer; } shootCD -= Time.deltaTime; } }
// Update is called once per frame void Update() { GameObject closestEnemy = null; float minDist = float.MaxValue; // find the closest enemyLayerMask foreach (GameObject enemy in battle.Enemies) { float dist = Vector3.Distance(transform.position, enemy.transform.position); if (dist < minDist) { minDist = dist; closestEnemy = enemy; } } Vector3 vec = (closestEnemy.transform.position - transform.position).normalized; // move towards them movement.HandleMovement(closestEnemy.transform.position, meleeAttackRange, false); // attack if close enough bool isPlayerClose = Physics.CheckSphere(transform.position, meleeAttackRange, playerLayerMask); bool isEnemyClose = Physics.CheckSphere(transform.position, meleeAttackRange, enemyLayerMask); if (isEnemyClose) { Attack(); } UpdateDamage(); }