这个第三人称角色控制器目前只写了PC端,想要做手机端的,有兴趣可以自己修改,如果不是商业项目,一个最简单的方法是在UGUI上,添加一个Image,在拖动的时候,打开此脚本,拖动结束时禁用此脚本,需要注意的是,这三个事件全都要写上:拖拽时,拖拽中,拖拽结束
直接上代码
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
using
UnityEngine;
using
System.Collections;
public
class
CameraFollow : MonoBehaviour
{
//距离
public
float
distance = 8;
//横向角度
public
float
rot = 0;
//纵向角度
private
float
roll = 10f * Mathf.PI * 2 / 360;
//目标物体
private
GameObject target;
public
GameObject Player;
//横向旋转速度
public
float
rotSpeed = 0.2f;
//纵向角度范围
private
float
maxRoll = 70f * Mathf.PI * 2 / 360;
private
float
minRoll = -40f * Mathf.PI * 2 / 360;
//纵向旋转速度
private
float
rollSpeed = 0.2f;
//距离范围
public
float
maxDistance = 22f;
public
float
minDistance = 5f;
//距离变化速度
public
float
zoomSpeed = 0.2f;
void
Start()
{
//设置目标
SetTarget(Player);
}
void
LateUpdate()
{
//一些判断
if
(target ==
null
)
return
;
if
(Camera.main ==
null
)
return
;
//目标的坐标
Vector3 targetPos = target.transform.position;
//用三角函数计算相机位置
Vector3 cameraPos;
float
d = distance *Mathf.Cos (roll);
float
height = distance * Mathf.Sin(roll);
cameraPos.x = targetPos.x +d * Mathf.Cos(rot);
cameraPos.z = targetPos.z + d * Mathf.Sin(rot);
cameraPos.y = targetPos.y + height;
Camera.main.transform.position = cameraPos;
//对准目标
Camera.main.transform.LookAt(target.transform);
//纵向旋转
Rotate();
//横向旋转
Roll();
//调整距离
Zoom();
}
//设置目标
public
void
SetTarget(GameObject target)
{
if
(target.transform.Find(
"cameraPoint"
) !=
null
)
this
.target = target.transform.Find(
"cameraPoint"
).gameObject;
else
this
.target = target;
}
//横向旋转
void
Rotate()
{
float
w = Input.GetAxis(
"Mouse X"
) * rotSpeed;
rot -= w;
}
//纵向旋转
void
Roll()
{
float
w = Input.GetAxis(
"Mouse Y"
) * rollSpeed * 0.5f;
roll -= w;
if
(roll > maxRoll)
roll = maxRoll;
if
(roll < minRoll)
roll = minRoll;
}
//调整距离
void
Zoom()
{
if
(Input.GetAxis(
"Mouse ScrollWheel"
) > 0)
{
if
(distance > minDistance)
distance -= zoomSpeed;
}
else
if
(Input.GetAxis(
"Mouse ScrollWheel"
) < 0)
{
if
(distance < maxDistance)
distance += zoomSpeed;
}
}
}
|