- Home /
How to make camera move backwards in relation to player (so behind player), regardless of y rotation of player and camera
So im having trouble doing this, and i need to know how to fix the following code. I want it so that when the mouse moves down, it becomes a top down view gradually (depending on how much the mouse is moved) and that requires rotation of the camera on the x axis, and movement on z and y axis, z axis is the problem.
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public float Sensitivity;
public float MaxDistance;
public float MaxAngle;
private float MouseY;
private float MouseYSet;
private float CameraAngle;
private float PlayerHead;
private float PlayerBack;
public Vector3 CameraDistance;
private Vector3 BackPos;
private Vector3 TopPos;
public GameObject CameraTarget;
void Start () {
PlayerHead = CameraTarget.transform.localPosition.y + CameraTarget.transform.localScale.y / 2;
PlayerBack = CameraTarget.transform.localPosition.z - CameraTarget.transform.localScale.z / 2;
}
void Update () {
// Look controls
MouseY -= Input.GetAxisRaw ("Mouse Y");
CameraAngle = Mathf.Clamp (CameraAngle + (MouseY - MouseYSet) * Sensitivity * 10, -MaxAngle, MaxAngle);
CameraDistance = new Vector3 (CameraTarget.transform.localPosition.x, Mathf.Clamp (CameraDistance.y + (MouseY - MouseYSet) * Sensitivity * 10, CameraTarget.transform.localPosition.y, PlayerHead + MaxDistance), Mathf.Clamp (CameraDistance.z + (MouseY - MouseYSet) * Sensitivity * 10, PlayerBack - MaxDistance, CameraTarget.transform.localPosition.z));
BackPos = new Vector3 (CameraTarget.transform.localPosition.x, CameraTarget.transform.localPosition.y, PlayerBack - MaxDistance);
TopPos = new Vector3 (CameraTarget.transform.localPosition.x, PlayerHead + MaxDistance, CameraTarget.transform.localPosition.y);
if (MouseY != 0)
{
transform.localRotation = Quaternion.Euler (CameraAngle, transform.localRotation.y, transform.localRotation.z);
transform.localPosition = new Vector3 (CameraDistance.x, CameraDistance.y, CameraDistance.z);
transform.localPosition = Vector3.Slerp (BackPos, TopPos, Sensitivity * 10);
MouseYSet = MouseY;
}
}
}
Answer by DaDonik · Jan 01, 2015 at 12:07 AM
"So im having trouble doing this, and i need to know how to fix the following code."
This is the exact problem you have and this will continue forever, until you sit down and actually try to learn programming and logical thinking from the ground up.
To answer your question: Use transform.forward and multipy it by a negative value. For example:
Vector3 CamPosBehindPlayer = -(transform.forward * 10.0f);
This will make the camera always stay 10 units behind the object the transform belongs to.
thanks for the help, but i decided to start over for efficiency reasons. :)