How to smoothly move a 3d camera to focus on an object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By WayfairSalesRep

I am developing a 3d turn based strategy game. Right now I have pawns that I can move around the grid and a camera I control with the arrow keys. I want the camera to also be able to follow the pawns when they are selected and when they move. The camera is the only child of a spatial node and the script is attached to the spatial node.

So far, I have been able to have the camera always centered on the pawns with the following code run through the _physics_process():

func _track_pawn(selected_pawn):
  var from = self.get_translation()
  var to = selected_pawn.get_translation() + Vector3(0, -3, 0)
  if from != to:
	var move = from.linear_interpolate(to, .2)
	self.set_translation(move)

The problem, of course, is that this prevents the camera from being moved with the arrow keys because it’s always following the selected pawn around. On the other hand, I can run the same code through an input function and the camera will scoot a little way towards the pawn whenever the input is pressed.

I can, of course, just use:

    func _track_pawn(selected_pawn):
      var to = selected_pawn.get_translation() + Vector3(0, -3, 0)
      self.set_translation(to)

and that will jump immediately to whichever pawn is selected when it’s selected, but it’s a bit jarring. I have also tried using a while loop, but the result is a crash:

func _track_pawn(var selected_pawn):
  var from = self.get_translation()
  var to = selected_pawn.get_translation() + Vector3(0, -3, 0)
  while from != to:
            var move = from.linear_interpolate(to, .2)
        	self.set_translation(move)

Any ideas?