So, I have a camera that has to follow the player that is a rolling ball, and i have the following script:
public GameObject target;
public Transform targetTransform;
public Rigidbody targetRigidbody;
private Transform camTransform;
private float distance = 20.0f;
private float height = 5.0f;
private float rotationDamping = 0.2f;
private float heightDamping = 10;
void Awake()
{
camTransform = this.gameObject.GetComponent<Transform>();
target = GameObject.FindWithTag("Player");
targetTransform = target.GetComponent<Transform>();
targetRigidbody = target.GetComponent<Rigidbody>();
}
void update(){
//set the starting values
float targetRotation;
float targetHeight = targetTransform.position.y + height;
float camRotation = camTransform.eulerAngles.y;
float camHeight = camTransform.position.y;
Vector3 flatSpeed= targetRigidbody.velocity;
flatSpeed.y = 0; //flat speed of the player
if (move == Vector3.zero)
targetRotation = camRotation;
else //record Y rotation of flat speed if it is moving
targetRotation = Quaternion.LookRotation(move).eulerAngles.y;
camHeight = Mathf.Lerp(camHeight, targetHeight, heightDamping * Time.deltaTime);
camRotation = Mathf.LerpAngle(camRotation, targetRotation, rotationDamping * Time.deltaTime);
Quaternion currentRotation; //get the wanted rotation obtained through lerping
currentRotation = Quaternion.Euler(0, camRotation, 0);
Vector3 wantedPos = targetTransform.position - (currentRotation * Vector3.forward * distance);
wantedPos.y = camHeight;
camTransform.position = wantedPos;
camTransform.LookAt(targetTransform);
//set position and rotation of the camera transform
}
now, this scripts works preatty fine, it follows smoothly the ball from the back while it moves.
my only problem is that, when i make the ball roll backward instead of forward the camera rotates 180 degrees and follows the player from the front insted, as you would expect. this gets the game quite confusing, and I really don’t know how to fix this script. Or if anyone knows of a better script and could be so kind to post it here.
Thank you in advance.