I am trying to get the camera to move such that it would place a target object in the middle of the view, without changing the camera's rotation. (Something like a RTS camera when you zoom to a unit or a building). Given the object's position, how do I know much to offset the camera's position by to get the desired effect?
The key is to use the negative of the camera's own transform.forward property to use as the offset. You then multiply this by the distance you want the offset to be away from the object.
Use something like this in your script that is attached to your camera. You would have a variable called 'viewDistance' which represents how far away your camera should be from the target objects.
var viewDistance = 20;
function MoveToTarget(target : Transform) {
var sourcePos = transform.position;
var destPos = target.position - transform.forward * viewDistance;
var i = 0.0;
while (i < 1.0) {
transform.position = Vector3.Lerp(sourcePos, destPos, Mathf.SmoothStep(0,1,i));
i += Time.deltaTime;
yield;
}
}
You would then call this "MoveToTarget" function and pass it the transform reference of whichever target it should move to.