Skip to main content

【精华】鼠标控制摄像机 (Mouse Orbit与Mouse Look合二为一)

(二.添加光线判断距离伸远缩进和人物透明)

//效果就是左右鼠标晃动改变人物x轴的轴向,//——–上下晃动改变摄像机围绕人朝向
//滚动滚轮伸远缩进
//距离近了使人物身上的材质隐藏

//改变人物透明度的时候需要右键添加一个"Material"透明材质 shader里面选择 Transparent下的Diffuse

using UnityEngine;
using System.Collections;

public class CameraWhirl : MonoBehaviour {

public GameObject target;
//旋转度数
float rotationX = 0F;
float rotationY = 0F;

//灵敏度
public float sensitivityX = 5F;
public float sensitivityY = 5F;
public float sensitivityZ = 5F;

//旋转范围
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -90F;
public float maximumY = 90F;

public float minimumZ = -20F;
public float maximumZ = 0.1F;

//相机与主角的距离
public float distance=-3.0F;

Quaternion originalRotation;
Vector3 angles ;
// Use this for initialization
void Start () {
distance=-3.0F;
originalRotation =target.transform.localRotation;
angles = transform.eulerAngles;
}

// Update is called once per frame
void Update () {
//滚动鼠标中轮 镜头缩进伸远
distance += Input.GetAxis("Mouse ScrollWheel")*sensitivityZ;
//~ mousescrollwheel_z += Input.GetAxis("Mouse ScrollWheel")*sensitivityZ;
if(distance>maximumZ)
{
distance=maximumZ;
}else if(distance<minimumZ)
{
distance=minimumZ;
}

//x轴 //——–左右晃动改变人物x轴的轴向
rotationX+=Input.GetAxis("Mouse X")*sensitivityX;
rotationX = ClampAngle (rotationX, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
target.transform.localRotation = originalRotation * xQuaternion;

//~ print("X:"+Input.GetAxis("Mouse X")+" "+"Y:"+Input.GetAxis("Mouse Y"));
//~ print("Q4:"+target.transform.localRotation);

//Y轴 //——–上下晃动改变摄像机围绕人朝向
rotationY+=Input.GetAxis("Mouse Y")*sensitivityY;
rotationY = ClampAngle (rotationY, minimumY, maximumY);
Quaternion rotation = Quaternion.Euler(-rotationY,rotationX, 0);
transform.rotation = rotation;
float R1=distance; //用来控制摄像机和人物的距离
//碰撞缩进伸远————
RaycastHit hit;
Vector3 spacevector =transform.position- target.transform.position;
if (Physics.Raycast (target.transform.position,spacevector, out hit,-R1)) {
// print (hit.point+" "+(hit.point- target.transform.position).magnitude);
Debug.DrawLine (target.transform.position, hit.point);
R1=-(hit.point- target.transform.position).magnitude; //碰撞点和人物坐标的距离
}
//—————————-
Vector3 V3=new Vector3(0.0F, 0.0F, R1);
transform.position =rotation*V3+target.transform.position; //用来控制摄像机和人物的距离

//人物透明
if(R1>-1.5F&&R1<-0.8)
{
target.renderer.material.color = new Color (1F, 1F,1F, 0.3F);
}
else if(R1>-0.8)
{
target.renderer.material.color = new Color (1F, 1F,1F, 0F);
}else
{
target.renderer.material.color = new Color (1F, 1F,1F,1F);
}
}

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);
}
}

//不足的地方1.人物透明不是插值2.摄像机向上看的时候能看到地的下面

不足的地方

  1. 人物透明不是插值
  2. 摄像机向上看的时候能看到地的下面