using UnityEngine public class CameraController MonoBehaviour public T

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
public float distance = 5.0f;
public float xSpeed = 8.0f;
public float ySpeed = 8.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = .5f;
public float distanceMax = 15f;
public bool invertMouse = false;
Rigidbody rb;
float x = 0.0f;
float y = 0.0f;
layerMask = ~(1 << LayerMask.GetMask("LightOnly"));
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
rb = GetComponent<Rigidbody>();
// Make the rigid body not change rotation
if (rb != null)
{
rb.freezeRotation = true;
}
}
void LateUpdate()
{
if (target && Time.timeScale > 0)
{
if (!invertMouse)
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
}else if (invertMouse)
{
x += -Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= -Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
}
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);
RaycastHit hit;
if (Physics.Raycast(target.position, transform.position, out hit, Mathf.Infinity, layerMask))
{
distance -= hit.distance+5;
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}