I am using a raycast method to make my character shoot the enemies. I have all of the guns and enemies set up. You use right click to aim the left click to shoot. You can only shoot while aiming. I am looking to make it so that when you press a key it centers the camera on the nearest enemy. How could I do this? Thanks in advance.
You need to find all of the enemies within the range of the weapon (use a trigger/collider or a Physics function), then find the one that is closest to the reticle. To find the one that is closest to the reticle, you want to compute the angle between the camera forward and the vector to the enemy. Code looks something like the following:
Enemy[] enemiesInRange = GetEnemiesInRange();
Enemy nearestEnemy = null;
float bestAngle = -1f;
foreach(Enemy enemy in enemiesInRange) {
Vector3 vectorToEnemy = enemy.transform.position - transform.position;
vectorToEnemy.normalize();
float angleToEnemy = Vector3.Dot(transform.forward, vectorToEnemy);
if(angleToEnemy > bestAngle)
{
nearestEnemy = enemy;
bestAngle = angleToEnemy;
}
}