Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class lockingOn : MonoBehaviour
- {
- public List<Transform> targets;
- public Transform selectedTarget;
- public string targetTag = "enemyChest";
- private Transform myTransform;
- //Use this for initialization
- void Start()
- {
- targets = new List<Transform>();
- selectedTarget = null;
- myTransform = transform;
- AddAllEnemies();
- }
- public void AddAllEnemies()
- {
- //Vector3 myVector3f;
- //myVector3f = new Vector3(0, 3f, 0);
- GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag);
- foreach (GameObject enemy in go)
- {
- AddTarget(enemy.transform);
- //AddTarget(enemy.transform + myVector3f);
- }
- }
- public void AddTarget(Transform enemy)
- {
- targets.Add(enemy);
- }
- private void SortTargetsByDistance()
- {
- targets.RemoveAll(target => target == null);
- targets.Sort(delegate (Transform t1, Transform t2)
- {
- return (Vector3.Distance(t1.position, myTransform.position).CompareTo)
- (Vector3.Distance(t2.position, myTransform.position));
- });
- }
- private void TargetEnemy()
- {
- if (selectedTarget == null)
- {
- SortTargetsByDistance();
- selectedTarget = targets[0];
- }
- else
- {
- int index = targets.IndexOf(selectedTarget);
- if (index < targets.Count - 1)
- {
- index++;
- }
- else
- {
- index = 0;
- }
- selectedTarget = targets[index];
- }
- }
- //Update is called once per frame
- void Update()
- {
- if (Input.GetKeyUp(KeyCode.Tab))
- {
- TargetEnemy();
- }
- }
- private void LateUpdate()
- {
- lockOnTab();
- }
- void lockOnTab()
- {
- if (Input.GetKeyUp(KeyCode.Tab))
- {
- Vector3 myVector;
- myVector = new Vector3(0, .1f, 0);
- Vector3 relativePos = selectedTarget.position - transform.position + myVector;
- // the second argument, upwards, defaults to Vector3.up
- Quaternion rotation = Quaternion.LookRotation(relativePos, myVector);
- transform.rotation = rotation;
- }
- if (selectedTarget != null)
- {
- Vector3 myVector;
- myVector = new Vector3(0, .1f, 0);
- Vector3 relativePos = selectedTarget.position - transform.position + myVector;
- // the second argument, upwards, defaults to Vector3.up
- Quaternion rotation = Quaternion.LookRotation(relativePos, myVector);
- transform.rotation = rotation;
- }
- if (Input.GetKeyUp(KeyCode.Q))
- {
- selectedTarget = null;
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement