Hi . So i have simple scene with player and some enemies . I have a script that finds closest enemy in some cone of influence ,and shoots at it .Now i need some other game object to get that same target that first game object currently have, and rotate towards it or look at .I have tried to use same script on second object
but i dont get what have i wanted because of rotation , cone of influence of first object and cone of influence of second object dont match when second object rotates toward target. So ruffly saying i need script from second object to get this target from first object script and rotate towards it .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FieldOfView : MonoBehaviour {
private Transform target;
public float FireRate;
private float fireCountdown;
public GameObject bulletPrefab;
public Transform firePoint;
public Transform partToRotate;
public float viewRadius;
[Range(0, 360)]
public float viewAngle;
public LayerMask targetMask;
public LayerMask obstacleMask;
public Transform attackTarget;
private Vector3 targetPos;
private Vector3 doAttackAngle;
[HideInInspector]
public List<Transform> visibleTargets = new List<Transform>();
private object closest_go;
void Start()
{
StartCoroutine("FindTargetsWithDelay", .5f);
}
IEnumerator FindTargetsWithDelay(float delay)
{
while (true)
{
yield return new WaitForSeconds(delay);
FindVisibleTargets();
}
}
public void FindVisibleTargets()
{
visibleTargets.Clear();
Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, viewRadius, targetMask);
float closest_dst = viewRadius;
Transform closest_go = null;
int count_ia = 0;
for (int i = 0; i < targetsInViewRadius.Length; i++)
{
Transform target = targetsInViewRadius[i].transform;
if (target.tag != "Enemy") continue;
Transform t_target = target.transform;
Vector3 dirToTarget = (t_target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, dirToTarget) < viewAngle / 2)
{
float dstToTarget = Vector3.Distance(transform.position, t_target.position);
if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask))
{
visibleTargets.Add(t_target);
count_ia++;
visibleTargets.Add(t_target);
if (dstToTarget < closest_dst)
{
doAttackAngle = dirToTarget;
closest_dst = dstToTarget;
closest_go = target;
}
}
}
}
if (count_ia == 0)
{
attackTarget = null;
}
else
{
attackTarget = closest_go;
Shoot();
}
}
void Shoot()
{
if (fireCountdown <= 0f)
{
fireCountdown = 1f / FireRate;
GameObject BulletGo = (GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Bullet Bullet = BulletGo.GetComponent<Bullet>();
if (Bullet != null)
{
Bullet.Seek(attackTarget);
}
}
fireCountdown -= Time.deltaTime;
}
public Vector3 DirFromAngle(float angleInDegrees, bool angleIsGlobal)
{
if (!angleIsGlobal)
{
angleInDegrees += transform.eulerAngles.y;
}
return new Vector3(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad), 0, Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));
}
}