转载请注明来自:http://blog.csdn.net/dadadie
利用鼠标对物体进行放大缩小和旋转大家都比较熟知,在此不多做解释直接上代码:
var target:Transform;
var xSpeed=250.0f;
var ySpeed=120.0f;
var yMinLimit = -60f;
var yMaxLimit = 60f;
var initDis : float = 15f;
var minDis : float = 1f;
var maxDis : float = 20f;
var wheelSpeed = 6f;
static var x = 0.0f;
static var y = 0.0f;
static var distance;
private var position;
private var rotation;
//标示是否其他脚本操作摄像机移动
private var CameraMoving :boolean = false;//iTween插件操作摄像机移动时,标示摄像机是否在移动
function Start ()
{
x = 45;
y = 0;
target = GameObject.Find("CameraFllowTarget").transform;
transform.rotation = Quaternion.Euler(y, x, 0);
transform.position = Quaternion.Euler(y, x, 0) * Vector3(0.0, 0, initDis) + target.position;
if (rigidbody)
rigidbody.freezeRotation = true;
}
function Update ()
{
if (target&&!CameraMoving){//iTween插件操作摄像机移动时,屏蔽鼠标更新摄像机位置
distance = Vector3.Distance(target.position,transform.position);
// 使用鼠标右键进行查看
// 0:左键 1:右键 2:中键
if(Input.GetMouseButton(1))
{
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
//y = ClampAngle(y, yMinLimit, yMaxLimit);
}
distance-= Input.GetAxis("Mouse ScrollWheel")*wheelSpeed;//获取鼠标中建响应
//distance = Mathf.Clamp(distance,minDis,maxDis);//距离取最大值和最小值
rotation = Quaternion.Euler(y, x, 0);
position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
static function ClampAngle (angle : float, min : float, max : float) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
//以下为和iTween结合的代码,如果只是放大缩小和旋转物体以上代码就可以了,以下代码不需要
public function StartiTween(GivenTarget:Transform){
CameraMoving = true;
target = GivenTarget;
}
public function CompleteiTween(){
CameraMoving = false;
x = transform.eulerAngles.y;
y = transform.eulerAngles.x;
}
需要特别注意的是:其中的x、y变量也即摄像机的旋转角,鼠标的操作最终导致x、y的变化,x、y的变化导致摄像机位置的变化,所以如果有别的脚本操作导致摄像机位置的变化,必须将摄像机变化update到鼠标操作的脚本,也即上述脚本。所以iTween插件moveto 针对摄像机进行漫游移动,漫游过程中需要对鼠标移动进行屏蔽,漫游后需要对摄像机漫游移动的量同步到上述脚本中。
iTween核心脚本
iTween.MoveTo(CameraMain,{"position":CameraDesTarget.transform,"looktarget":LookTarget.transform,"onstart":"OnStartiTween","onstarttarget":transform.gameObject,"onstartparams":LookTarget.transform,"oncomplete":"OnCompleteiTween","oncompletetarget":transform.gameObject,"oncompleteparams":"completeiTween","time":4.0f,"delay":0.0f});
public function OnStartiTween(GivenTarget:Transform){
CameraScript.StartiTween(GivenTarget);
}
public function OnCompleteiTween(message:String){
CameraScript.CompleteiTween();
}
具体api参照:http://itween.pixelplacement.com/index.php
其中漫游开始进行了中心物体的改变,漫游完成对摄像机的位置相关参量进行了更新。