We have been making a pirate game, and to make it easier for the player to find the enemies, we plan to have a part of a compass point towards the closest enemy. To do that, we have placed a small cube (designated “Pointer”) to the player’s ship, as well as a compass on the canvas. However, we have bot been able to make the code calculate and choose which enemy in an array is closest. Here is the code in C#:
using UnityEngine;
using System.Collections;
public class Compass_Script : MonoBehaviour
{
public GameObject compassUnder;
public GameObject compassOver;
public GameObject playerShip;
public GameObject pointer;
public GameObject enemyShip;
public GameObject camera;
public float angle;
public float offset = 180;
private GameObject[] enemies;
public float[] distanceToTarget;
public GameObject target;
public Vector3[] dis;
public float[] a;
// Use this for initialization
void Start()
{
enemies = GameObject.FindGameObjectsWithTag("enemy");
enemyShip = enemies[1];
}
// Update is called once per frame
void Update()
{
targeting();
compassUnder.transform.localEulerAngles = new Vector3(0.0f, 0.0f, +playerShip.transform.localEulerAngles.y - camera.transform.localEulerAngles.y - 180);
pointer.transform.LookAt(enemyShip.transform.position);
if (Vector3.Dot(pointer.transform.forward, camera.transform.right) > 0.0f)
{
angle = Vector3.Angle(camera.transform.forward, pointer.transform.forward) * (-1.0f);
}
else
{
angle = Vector3.Angle(camera.transform.forward, pointer.transform.forward);
}
compassOver.transform.localEulerAngles = new Vector3(0.0f, 0.0f, (angle - compassUnder.transform.localEulerAngles.z));
}
private void targeting()
{
for(int i = 0; i >= enemies.Length;)
{
distanceToTarget _= Vector3.Distance(GameObject.Find("pointer").transform.position, enemies*.transform.position);*_
//Vector3.Distance(GameObject.Find(“Pointer”).transform.position, enemies*.transform.position).GetHashCode;*
i++;
}
}
private void rulerDis()
{
for(int i = 0; i >= distanceToTarget*;)*
{
for(int j = 0; j >= distanceToTarget[j]
{
a[j] = (distanceToTarget[j] - distanceToTarget[j+1]);
}
if(a < a[i+1])
{
enemyShip = enemies*;*
Debug.Log("enemy is " + i);
}
}/*catch()
{
Debug.Log(“Failed to compare”);
}*/
}
private void worked()
{
Debug.Log(“it worked”);
}
}
The important thing for us is to make the pointer choose the closest enemy to face, and change if another enemy comes closer.
We thank your for your help and interest.