title: Unity - Making Camera Lock on To Enemy and stay behind player?
body: <p>I am attempting to create a Camera that moves with the Player but locks onto an enemy when the player clicks the lock on button. The behaviour is almost working as I want it, the camera locks onto the target. And when the player stand in-front of the target it works fine. However as soon as the player runs past the target, the camera behaves strangely. It still looks at the Enemy, however it does not stay behind the player. Here is the code that dictates the behaviour:</p>
  
  <pre><code>if(MouseLock.MouseLocked &amp;&amp; !lockedOn){ // MOUSE CONTROL:
      Data.Azimuth += Input.GetAxis("Mouse X") * OrbitSpeed.x;
      Data.Zenith    += Input.GetAxis("Mouse Y") * OrbitSpeed.y;
  } else if(lockedOn) { // LOCKON BEHAVIOUR:
      FindClosestEnemy();
  }
  
  if (Target != null) {
      lookAt += Target.transform.position;
      base.Update ();
      gameObject.transform.position += lookAt;
  if(!lockedOn){
       gameObject.transform.LookAt (lookAt);
  } else if(enemyTarget != null) {
       Vector3 pos1 = Target.transform.position ;
       Vector3 pos2 = enemyTarget.transform.position ;
       Vector3 dir = (pos2 - pos1).normalized ;
       Vector3 perpDir = Vector3.Cross(dir, Vector3.right) ;
       Vector3 midPoint = (pos1 + pos2) / 2f;
       gameObject.transform.LookAt (midPoint);
   }
  
  }
  </code></pre>
  
  <p>And the Code for Finding the nearest Enemy:</p>
  
  <pre><code>void FindClosestEnemy ()  {
       int numEnemies = 0;
       var hitColliders = Physics.OverlapSphere(transform.position, lockOnRange);
       foreach (var hit in hitColliders) {
           if (!hit || hit.gameObject == this.gameObject || hit.gameObject.tag == this.gameObject.tag){
               continue;
           }
           if(hit.tag != "Enemy") // IF NOT AN ENEMY: DONT LOCK ON
               continue;
           var relativePoint = Camera.main.transform.InverseTransformPoint(hit.transform.position); 
           if(relativePoint.z &lt; 0){
               continue;
           }
           numEnemies += 1;
           if(enemyTarget == null){
               print ("TARGET FOUND");
               enemyTarget = hit;
           }
       }
       if(numEnemies &lt; 1){
           lockedOn = false;
           enemyTarget = null;
       }
   }
  </code></pre>
  
  <p>As I said, teh behaviour almost works as expected, however I need the camera to stay behind the player whilst locked on and it must face the enemy/midPoint between the enemy and player. How can this be done? Thank you for your time.</p>