Unity相机的跟随、拉进拉远、 旋转的效果实现

 

将脚本挂到相机上

private Transform player;//角色
private Transform tran;//相机
private Vector3 offsetPoint;//位置偏移
private bool isRotate = false;//是否旋转
public float distence = 0;//相机与角色的距离
public float scrollSpeed = 10f;//拉进拉远速度
public float rotateSpeed = 2f;//视野旋转速度
void Start(){
tran = transform;
player = GameObject.FindGameObjectWithTag("Player").transform;
offsetPoint = transform.position - player.position;
//相机朝向角色
tran.LookAt(player.position);
}
void Update(){
//相机跟随
tran.position = player.position + offsetPoint;
//实现视野的旋转效果
RotateView();
//处理视野拉进拉远的效果
ScrollView();
}
void ScrollView(){
//把向量换成长度
distence = offsetPoint.magnitude;
//距离加减获取的鼠标中键的值 鼠标中键向前 正值(视野拉远) 向后 负值(视野拉近)
distence += Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
distence = Mathf.Clamp(distence, 2, 20);
//求新的偏移量 单位向量乘以长度
offsetPoint = offsetPoint.normalized * distence;
}
void RotateView(){
//Input.GetAxis("Mouse X") 鼠标水平方向的滑动距离
//Input.GetAxis("Mouse Y") 鼠标垂直方向的滑动距离
if (Input.GetMouseButtonDown(1)){
isRotate = true;
}
if (Input.GetMouseButtonUp(1)){
isRotate = false;
}
if (isRotate){
//以角色为中心旋转 水平旋转
tran.RotateAround(player.position, player.up, Input.GetAxis("Mouse X") * rotateSpeed);
Vector3 tempPos = tran.position;
Quaternion tempRotate = tran.rotation;
//视野上下旋转
tran.RotateAround(player.position, tran.right, -Input.GetAxis("Mouse Y") * rotateSpeed);
float x = tran.eulerAngles.x;
//限制旋转范围
if (x < 10 || x > 80){
//重置为原来位置
tran.position = tempPos;
tran.rotation = tempRotate;
}
}
//更新偏移量
offsetPoint = transform.position - player.position;
}

posted @ 2019-10-09 10:57  C#初学者—Damon  阅读(1855)  评论(0编辑  收藏  举报