- Home /
Camera turns to the front when reversing car
Hello!
When I started making my game back in 2014 I followed a video tutorial and created a camera script with the help of that. When reversing though, the camera turns to the front of the car and I don't like that. How would I get the camera to always look at the back of the car?
using UnityEngine;
using System.Collections;
public class CarCameraScript : MonoBehaviour
{
public Transform car;
public float distance = 6.4f;
public float height = 1.4f;
public float rotationDamping = 3.0f;
public float heightDamping = 10.0f;
public float zoomRatio = 0.5f;
public float defaultFOV = 60f;
private Vector3 rotationVector;
void LateUpdate ()
{
float wantedAngle = rotationVector.y;
float wantedHeight = car.position.y + height;
float myAngle = transform.eulerAngles.y;
float myHeight = transform.position.y;
myAngle = Mathf.LerpAngle (myAngle, wantedAngle, rotationDamping * Time.deltaTime);
myHeight = Mathf.Lerp (myHeight, wantedHeight, heightDamping * Time.deltaTime);
Quaternion currentRotation = Quaternion.Euler (0, myAngle, 0);
transform.position = car.position;
transform.position -= currentRotation * Vector3.forward * distance;
Vector3 temp = transform.position; //temporary variable so Unity doesn't complain
temp.y = myHeight;
transform.position = temp;
transform.LookAt (car);
}
void FixedUpdate ()
{
Vector3 localVelocity = car.InverseTransformDirection (car.rigidbody.velocity);
if (localVelocity.z < -0.5f) {
Vector3 temp = rotationVector; //because temporary variables seem to be removed after a closing bracket "}" we can use the same variable name multiple times.
temp.y = car.eulerAngles.y + 180;
rotationVector = temp;
} else {
Vector3 temp = rotationVector;
temp.y = car.eulerAngles.y;
rotationVector = temp;
}
float acc = car.rigidbody.velocity.magnitude;
camera.fieldOfView = defaultFOV + acc * zoomRatio * Time.deltaTime; //he removed * Time.deltaTime but it works better if you leave it like this.
}
}
Answer by InvincibleCat · Feb 12, 2015 at 11:31 PM
You can make things easy having 2 cameras and activate the one you need ;)
Yes but why do you want just one ?
(by the way, can you please accept my answer here http://answers.unity3d.com/questions/898257/time-difference-between-race-time-and-best-time.html you just closed the post...)
You can have 2 tranforms representing your camera state and swith to this 2 transforms -> your camera become a child and then set the localPosition and the localRotation to 0 (of your camera)
What I will do is having a new script that will have 2 gameobjects (the 2 cameras) and will activate/desactivate the cameras in your if/else statement (with SetActive method)
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Reverse Camera Twitches 1 Answer
Laggy Camera 2 Answers
Multiple Cars not working 1 Answer