Hey basically im trying to make a camera that follows the player(already works) and then i can use the A and D keys to rotate around the player left or right. the problem is that the camera doesnt actually rotate around, it kinda of zooms in and out. here’s the code;
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target;
//camera will follow the target.
//camera is going to be that many units from the player
public float Height = 10;
public float radius = 10;
public float angle = 0;
public float rotationalSpeed = 1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
float cameraX = target.position.x + (radius * Mathf.Cos(angle));
float cameraY = target.position.y + Height;
float cameraZ = target.position.z + (radius * Mathf.Cos(angle));
transform.position = new Vector3(cameraX, cameraY, cameraZ);
if (Input.GetKey(KeyCode.A))
{
angle = angle - rotationalSpeed * Time.deltaTime;
}//end of if
else if (Input.GetKey(KeyCode.D))
{
angle = angle + rotationalSpeed * Time.deltaTime;
}//end of else if
transform.LookAt(target.position);
}//end of update
}//end of CameraFollow Class
the target is set to be the gameobject of player in the scene yet it doesnt rotate aorund the y axis around him. any ideas?
Your basically taking a circle slice around the player then moving it up 10 units. So to get the x,z co-ordinates picture them as x,y points around a circle centered at the origin with radius R
z = sin(angle)
x= cos (angle)
Since you were taking cosine both times you were just geting the x-component each time so it the camera would act like a spring along the x=z line zooming in and out as you pressed A,D.
Here’s a fixed version that also converts the degrees to radians. You will need to adjust the rotational speed accordingly. I have it setup in degrees per second, which seems the easiest to use.
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
public Transform target;
//camera will follow the target.
//camera is going to be that many units from the player
public float Height = 10;
public float radius = 10;
public float angle = 0;
// make this in degrees per Second
// Setting it to 36 = 10 seconds to fully rotate around
public float rotationalSpeed = 36f;
// Update is called once per frame
void Update()
{
float cameraX = target.position.x + (radius * Mathf.Cos(Mathf.Deg2Rad*angle));
float cameraY = target.position.y + Height;
float cameraZ = target.position.z + (radius * Mathf.Sin(Mathf.Deg2Rad*angle));
transform.position = new Vector3(cameraX, cameraY, cameraZ);
if (Input.GetKey(KeyCode.A))
{
angle = angle - rotationalSpeed * Time.deltaTime;
}//end of if
else if (Input.GetKey(KeyCode.D))
{
angle = angle + rotationalSpeed * Time.deltaTime;
}//end of else if
transform.LookAt(target.position);
}//end of update
}//end of CameraFollow Class