Hello, just been writing a script in Javascript for a lock on system.
Trying to get the system to be similar to Zelda. So when I press a button the player looks at the nearest enemy and always faces them while the “lock-on” button is held down.
Right now the closest enemy is being determined but the problem is when I hold down “T” the player just jitters rather than looking straight at the enemy…
#pragma strict
/*=================
Lock-on to Enemy
=================*/
var targeting : boolean = false;
var enemyLocations : GameObject[];
var closest : GameObject;
function Update() {
if(Input.GetKeyDown(KeyCode.T)) // If " T " is held down.
{
Debug.Log("FindingClosestEnemy");
FindClosestEnemy(); // Run this function
Debug.Log(closest);
if (targeting == false)
{
targeting = true; // Targetting becomes true
}
}
if(Input.GetKeyUp(KeyCode.T))
{
targeting = false; // When " T " comes back up, targetting becomes false.
}
if(targeting == true)
{
LockOn(); // Lock-on when targetting becomes true;
}
}
function FindClosestEnemy() : GameObject {
enemyLocations = GameObject.FindGameObjectsWithTag("Enemy"); // Find all game objects with tag Enemy
var distance = Mathf.Infinity;
var position = transform.position;
for (var go : GameObject in enemyLocations) // Go through all enemy tags and find the nearest one.
{
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
}
function LockOn() {
transform.LookAt(closest.transform); // Look at the closest enemy.
Debug.Log("looking at closest");
}