Hi everyone. I am at the moment developing a game where you can spawn small soldiers that will attack the enemy small soldiers.
Everyone is going really well and working except i want my soldiers to choose the enemies that are closets (inside of the minDistance required to shot of course) and then start shooting them.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class frenchMoveAndShoot : MonoBehaviour
{
float waitTimer = 3;
public float verticalTime = 1f;
float minLeftAndRightSpeed = 0.25f;
float maxLeftAndRightSpeed = 1f;
float minSpeed = 0.75f;
float maxSpeed = 3;
float minDist = 7;
public GameObject Enemy;
public Vector3 bulletOffset = new Vector3(0.5f, 0, 0);
public GameObject bulletPrefab;
public float fireDelay = 3;
float cooldownTimer = 0;
IEnumerator Start()
{
float startTimer = Random.Range(0.5f, 2.9f);
yield return new WaitForSeconds(startTimer);
StartCoroutine(moveLeft());
}
// Update is called once per frame
void Update()
{
Enemy = GameObject.FindGameObjectWithTag("German");
float distance = Vector3.Distance(transform.position, Enemy.transform.position);
if (distance <= minDist)
{
transform.LookAt(Enemy.transform);
Shoot();
}
else
{
float Speed = Random.Range(minSpeed, maxSpeed);
transform.Translate(Vector3.forward * Speed * Time.deltaTime);
}
}
IEnumerator moveLeft()
{
float t = verticalTime;
while (t > 0f)
{
float moveLeftAndRightRandomSpeed = Random.Range(minLeftAndRightSpeed, maxLeftAndRightSpeed);
transform.Translate(Vector3.left * moveLeftAndRightRandomSpeed * Time.deltaTime);
t -= Time.deltaTime;
yield return new WaitForEndOfFrame();
}
yield return new WaitForSeconds(waitTimer);
StartCoroutine(moveRight());
}
IEnumerator moveRight()
{
float t = verticalTime;
while (t > 0f)
{
float moveLeftAndRightRandomSpeed = Random.Range(minLeftAndRightSpeed, maxLeftAndRightSpeed);
transform.Translate(Vector3.right * moveLeftAndRightRandomSpeed * Time.deltaTime);
t -= Time.deltaTime;
yield return new WaitForEndOfFrame();
}
yield return new WaitForSeconds(waitTimer);
StartCoroutine(moveLeft());
}
void Shoot()
{
cooldownTimer -= Time.deltaTime;
if (cooldownTimer <= 0)
{
cooldownTimer = fireDelay;
Vector3 offset = transform.rotation * bulletOffset;
Instantiate(bulletPrefab, transform.position + offset, transform.rotation);
}
}
}