I am searching in the whole internet for a (third person) aiming script. something like in GTA4 or the Zelda game.
so that the player will will look at/aiming an object while the right mouse button is pressed and he is in a pre-definded range to the enemy. and when you release the right mouse button the player will end focusing on the enemy.
Loop through the collected enemies and compare the distance to the player
Find the smallest distance and store the index
If you have a match, use the autoAim vector to orient the player
If you already have a list containing a reasonable amount of “active” enemies, use that list. If not, you can use the Physics.OverlapSphere to collect all enemies in range. (using a layer mask).
Collect the enemies using the physics.OverlapSphere when the right mouse button is initially clicked.
Untested C# code!(Should translate to unityScript easily though)
Transform player;
int layerMask;
float radius;
Collider[] targets = Physics.OverlapSphere(player.position, radius, layerMask); // grab all targets in range
Vector3 autoAim;
if (targets != null)
{
int index;
float distance = radius * radius; // avoid doing square roots, test against the squared distance
for (int i = 0; i < targets.Length; i++)
{
float current = (targets[i].transform.position - player.position).sqrMagnitude;
if (current < distance)
index = i;
}
autoAim = (targets[index].transform.position - player.position); // autoAim direction, you may have to adjust the Y axis depending on the object pivot
}
However I would rather test against the angle between the player and the target, as an enemy behind you may be the closest one. Also, if you have obstacles in your scene, you should also add a raycast test to find out if the target is blocked.
Another thing to keep in mind is when to update the auto-aim. For example, if you found the best target and the player “shoots?” at the target, but another enemy is getting closer, you might not want the autoAim to switch to the new target. Or if the target dies, but the player is still pressing the mouse button…