Cannot tween camera to a nice smooth stop.


I am currently using a camera to track a golf ball in the air. The camera tracks the ball from above and then when gravity gets the better of the ball, it drops away from the camera leaving a view in the sky of the ball on the fairway below. My camera then begins to zoom back to the (close-up) distance to the ball as specified in the script, zooming quickly (as i have specified).

How can I tween the camera to a stop when it reaches the ball again? Looks pretty crude at the minute.

Here is the script I am using:

var myCamera : Transform;
var target : Transform;
var desiredDist  = 7;
var minDist = 7;
var maxDist = 1000;
var speed = 40;
function Update () 
    var f = Mathf.MoveTowards(myCamera.position.y - target.position.y, desiredDist, speed * Time.deltaTime);
    f = Mathf.Clamp(f, minDist, maxDist);
    myCamera.position = target.position + Vector3(0, f, 0);

At the minute the camera just crashes to a stop with this method. There is also a little ‘judder’ when the ball falls past the desired distance too, that I’m trying to smooth out, but as I’m quite new to JS I just can’t figure it out. Thanks for any help.

It’s not impossible. Part of the problem might be the use of clamp. That’s going to override the smoothing that occurs in movetowards. What you probably want to do is multiply your speed by a function of the camera’s distance from the ball. That means that the further the ball is away from the camera, the more you’re going to add to a multiplier. You could do something like the following, although it’s probably not going to work as is for your usecase, but with some fiddling it will.

float speedModifier = 1 + (ballPos.position - transform.position).sqrMagnitude - (desiredDist * desiredDist);

Then you’d also multiply your speed value by the above value.

var f = Mathf.MoveTowards(myCamera.position.y - target.position.y, desiredDist, speed * speedModifier * Time.deltaTime);

Let me know how it worked for you.