so i created a method by which i can draw a lockon on enemies that are near by . Unfortunately once it locks on to target it maintains that target as the only target.
here is the entire code
only three (3) main functions.
you attach the script to your player gameobject.
can you help me get this thing to work correctly >.<
thanks in advance .
and sorry for the messy code ^^
using UnityEngine;
using System.Collections;
public class Lockon : MonoBehaviour {
public Texture2D Crosshair;
private Camera myCamera;
private Transform myTransform;
private Vector3 worldPosition = new Vector3();
private Vector3 screenPosition = new Vector3();
private Vector3 cameraRelativePosition = new Vector3();
private float minimumDistanceZ = 30.0f;
private float adjustment = 1;
private GUIStyle LockonStyle = new GUIStyle();
private float dist2;
public Transform enemyship;
float distance = Mathf.Infinity;
public GameObject closest;
// find the closest enemy ----------------start--------------
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("lazerhit");
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
//-----------------------End-----------------------------------
// Update is called once per frame
void Update () {
// set enemyship to the closest gameovject with the tag "lazerhit"
enemyship =FindClosestEnemy().transform;
// GetType distance from player to enemy
dist2 = Vector3.Distance(enemyship.position, gameObject.transform.position);
//-------------------------------------------
myTransform = enemyship;
myCamera = Camera.main;
//Capture whether the player is in front or behind the camera.
cameraRelativePosition = myCamera.transform.InverseTransformPoint(enemyship.transform.position);
LockonStyle.normal.background = Crosshair;
FindClosestEnemy();
}
void OnGUI (){
if(cameraRelativePosition.z > minimumDistanceZ && dist2 < 400.0f)
{
worldPosition = new Vector3(myTransform.position.x, myTransform.position.y + adjustment,
myTransform.position.z);
screenPosition = myCamera.WorldToScreenPoint(worldPosition);
GUI.Label(new Rect(screenPosition.x - 40 / 2,Screen.height - screenPosition.y - 20,40, 40),"",LockonStyle);
}
}
}