using UnityEngine; using System.Collections; public class CameraClass : MonoBehaviour { public PlayerControl target; private const float deg = Mathf.Deg2Rad; private float distance = 5.0f, angle = deg * 135.0f, targetangle = 0.0f, yoffset = 4.8f, temp = 0.0f; private const float twoPi = Mathf.PI * 2; private const float deg45 = Mathf.PI / 4; private Vector3 point; void Start () { targetangle = angle; } void Update () { if(Input.GetKeyDown("[4]")) targetangle += deg45; if(Input.GetKeyDown("[6]")) targetangle -= deg45; //Move the camera left and right at a static speed, and update the target angle accordingly if(Input.GetKey("[4]")) { angle += deg*1.5f; if(angle > targetangle) targetangle += deg45; } else if(Input.GetKey("[6]")) { angle -= deg*1.5f; if(angle < targetangle) targetangle -= deg45; } //Move the camera toward/away from the player else if(Input.GetKey("[8]") && camera.orthographicSize > 3.5f) { camera.orthographicSize -= 0.1f; yoffset -= .025f; } else if(Input.GetKey("[2]") && camera.orthographicSize < 7f) { camera.orthographicSize += 0.1f; yoffset += .025f; } //If the current camera angle is too close to the target angle when key is released, //increment the target angle to avoid an abrupt stop if(Input.GetKeyUp("[4]") || Input.GetKeyUp("[6]")) { temp = targetangle - angle; if(Mathf.Abs(temp) < deg*15) targetangle += deg45*Mathf.Sign(temp); } updateCamera(); } public void updateCamera() { //If the camera rotation keys are not being pressed, if(!Input.GetKey("[4]") && !Input.GetKey("[6]")) { if(angle != targetangle) { //Decelerate rotation toward target angle until it is reached //Rotation speed is capped at deg temp = (targetangle - angle) / 16f; if(Mathf.Abs(temp) > deg*1.5f) temp = deg*1.5f*Mathf.Sign(temp); angle += temp; } //Correct the floating point number when within a small range of the target angle if(angle < targetangle + 0.005f && angle > targetangle - 0.005f) { angle = targetangle; angle = keepInBounds(angle); targetangle = angle; } } //Follow Player point = target.transform.position; float xoffset = Mathf.Sin(angle) * distance; float zoffset = Mathf.Cos(angle) * distance; transform.position = new Vector3(point.x + xoffset, point.y + yoffset, point.z + zoffset); transform.LookAt(new Vector3(point.x, point.y - 0.5f, point.z)); } //Keeps the angle variable between 0 and pi*2 public float keepInBounds(float a) { if(a < 0) a += twoPi; if(a > twoPi) a -= twoPi; return a; } //Returns a relative angle in Radians where "steps" is the number of //45 degree turns clockwise from "toward" the camera public float getDirection(int steps) { return keepInBounds(this.angle + (deg45 * steps)); } public float getAngle() { return angle; } }