I have a camera script that follows the player and i need the camera’s rotation to be relative of the targets rotation. Example: The camera will view the player at a top down angle that is constantly turning with the player. Right now what its doing is the camera is following the player, but when i turn the player using the arrows the camera is not turning with the player.
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target;
public float smoothTime = 0.1f;
public float speed = 3.0f;
public float followDistance = 10f;
public float verticalBuffer = 1.5f;
public float horizontalBuffer = 0f;
private Vector3 velocity = Vector3.zero;
public Quaternion rotation = Quaternion.identity;
void Update () {
Vector3 targetPosition = target.TransformPoint(new Vector3(horizontalBuffer, followDistance, verticalBuffer));
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
rotation.eulerAngles = new Vector3(90, target.localRotation.y, target.localRotation.z);
rotation.y = target.rotation.y;
}
}
public class TransformToPlayer : MonoBehaviour {
public Transform target;
public float speed;
void Update() {
transform.eulerAngles = new Vector3(0, target.transform.eulerAngles.y, 0);
}
}
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target;
public float smoothTime = 0.1f;
public float speed = 3.0f;
public float followDistance = 10f;
public float verticalBuffer = 1.5f;
public float horizontalBuffer = 0f;
private Vector3 velocity = Vector3.zero;
public Quaternion rotation = Quaternion.identity;
public float yRotation = 0.0f;
void Update () {
Vector3 targetPosition = target.TransformPoint(new Vector3(horizontalBuffer, followDistance, verticalBuffer));
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
//this is the code that solves the problem
transform.eulerAngles = new Vector3(90, target.transform.eulerAngles.y, 0);
//------------------------------------------------------------------------
}
}
Put that in the update loop and see if it works–I think it should work as you envision as long as the player is ONLY rotating on the x/y axis–one issue with this might be that it copies the initial z rotation of the player object–but it shouldn’t change after that. it’s worked for me in 2d projects–I’m not sure how well for 3d.
You should only need to rotate the camera on one axis–it should be your y or x axis. Try using the y axis first and then the x. I would also initialize the floats outside the update loop and define them in the loop–but this is a quick dirty test.