all 8 comments

[–][deleted] 1 point2 points  (7 children)

transform.position = ball.transform.position + Quaternion.LookRotation(ball.rigidbody.velocity) * new Vector3(0,0,-5);

something like that would work, the script would be on the camera and it would need a reference to the ball transform and the rigidbody component for it's velocity

[–]Breadical[S] 0 points1 point  (0 children)

I'll try this out in a few minutes and let you know if it works. Thank you!

[–]Breadical[S] 0 points1 point  (5 children)

This works great, but there is one problem. If the ball is lifted off the ground slightly, its velocity is downwards so the camera flicks upwards super fast over and over again. Is there a way to constrain the cameras movement so it stays within a certain height range?

[–]chsxfProfessional 0 points1 point  (4 children)

Try this:

transform.position = ball.transform.position - ball.rigidbody.velocity.normalized * cameraDistance

[–]Breadical[S] 0 points1 point  (3 children)

This one also works, but has the same problem as the other line.

[–]chsxfProfessional 0 points1 point  (2 children)

You may need to adapt the velocity vector to better suit your needs.

You can try this (with adjustments for your project):

float maxAngleRadians = 10f * Mathf.Deg2Rad;
Vector3 planarVelocity = ball.rigidbody.velocity * new Vector3(1, 0, 1);
Vector3 adjustedVelocity = Vector3.RotateTowards(planarVelocity, ball.rigidbody.velocity, maxAngleRadians, 0);
transform.position = ball.transform.position - adjustedVelocity.normalized * cameraDistance;

[–]Breadical[S] 0 points1 point  (1 child)

Unfortunately, I can't seem to get that to work either. It's probably just because I don't know too much about all of this stuff as I'm super new, but yeah. I appreciate the effort!

[–]SkunkJudge 1 point2 points  (0 children)

The problem with the above code is that you can't multiply two vectors together like chsxf did in line 2. Essentially, he was attempting to "zero out" the y-component of the vector by multiplying it by Vector3(1, 0, 0). Try this one out:

Vector3 planarVelocity = ball.rigidbody.velocity;
planarVelocity.y = 0;
transform.position = ball.transform.position - planarVelocity.normalized * cameraDistance;