unity 固定摄影机

#pragma strict
@script AddComponentMenu("Level4/Cameras/FixedCamera")
///////////////////////////////////////////////////////////
//固定角度摄影机,主体
//思路:用变量offsetPos存放,摄影机与target的位置关系,
//修改offsetPos可以对摄影机的位置实现不同的控制.
///////////////////////////////////////////////////////////
/**摄影机的目标*/
var target:Transform;
/**与目标位置的偏移向量*/
var offsetPos:Vector3 = Vector3(0,4,-4);
/**跟随target的速度*/
var followSpeed:float = 0.2;

function Update(){
	if(target){
		UpdatePosition();
	}
}
function Start(){
	SetupCamera();
}
/**
设定 摄影机的旋转量.
*/
function SetupCamera(){
	transform.rotation = Quaternion.LookRotation(-offsetPos);
}
//更新 摄影机的坐标.
private function UpdatePosition(){
	var targetPos:Vector3 = target.position + offsetPos;
	transform.position = Vector3.Lerp(transform.position,targetPos,followSpeed);
}



#pragma strict
@script AddComponentMenu("Level4/Cameras/FixedCameraMouseMove")
@script RequireComponent(FixedCamera);
//////////////////////////////////////////////////////
///固定角度摄影机,鼠标控制
//////////////////////////////////////////////////////
private var target:Transform;
private var fixedCamera:FixedCamera;

private var totalOffset:Vector3 = Vector3.zero;

/**移动的速度*/
var moveSpeed:float = 0.2;
/**xz平面,左下角坐标*/
var minPos:Vector3 = Vector3(-3,0,-6);
/**xz平面,右上角坐标*/
var maxPos:Vector3 = Vector3(3,0,1);

function Start(){
	fixedCamera = GetComponent(FixedCamera);
	target = fixedCamera.target;
}

function Update(){
	MouseMoveCamera();
}

/**
	通过鼠标移动视野.
	h,x方向.
	v,z方向.
*/
private function MouseMoveCamera(){
	var h:float = Input.GetAxis("Mouse X");
	var v:float = Input.GetAxis("Mouse Y");
	 
	var dir:Vector3 = Vector3(h,0,v);
		dir *= moveSpeed;
	var offsetPos:Vector3 = fixedCamera.offsetPos + dir;
	
	//-----------------------------------限制.
	offsetPos.x = Mathf.Clamp(offsetPos.x , minPos.x , maxPos.x);
	offsetPos.z = Mathf.Clamp(offsetPos.z , minPos.z , maxPos.z);
	fixedCamera.offsetPos = offsetPos;
}



#pragma strict
@script RequireComponent(FixedCamera)

//////////////////////////////////////////////////////
///固定角度摄影机.滚轮缩放
//////////////////////////////////////////////////////
private var fixedCamera:FixedCamera;
/**滚轮响应速度*/
var viewSpeed:float = 2;
/**yz平面,前下角坐标*/
var minPos:Vector3 = Vector3(0,4,-8);
/**yz平面,后上角坐标*/
var maxPos:Vector3 = Vector3(0,8,-4);

function Start(){
	fixedCamera = GetComponent(FixedCamera);
}

function Update () {
	UpdateView();
}

//更新视野.通过更新摄影机坐标来实现.
private function UpdateView(){
	var val:float = Input.GetAxis("Mouse ScrollWheel");
	if(val != 0){
		val *= viewSpeed;
		
		var yPos:float = -val;
		var zPos:float = val;
		var offsetPos:Vector3 = fixedCamera.offsetPos;
			offsetPos += Vector3(0,yPos,zPos);
			offsetPos.y = Mathf.Clamp(offsetPos.y , minPos.y , maxPos.y);
			offsetPos.z = Mathf.Clamp(offsetPos.z , minPos.z , maxPos.z);
		fixedCamera.offsetPos = offsetPos;
	}
}

你可能感兴趣的:(cameras)