Unity摄像机 向指定位置移动旋转 C#脚本

using UnityEngine;
using System.Collections;

public class CameraCtrl : MonoBehaviour {
float frameCount = 50.0f; // 希望多少帧内完成场景转移
// 目标位置:写死在代码里了
float target_px = -17.22f;
float target_py = 0.0f;
float target_pz = -15.0f;


float target_rx = 40.0f;
float target_ry = -20.0f;
float target_rz = 0.0f;
// 当前位置:start函数中设定
float cur_px;
float cur_py;
float cur_pz;


float cur_rx;
float cur_ry;
float cur_rz;
// 步长:若没到达目的地,则步长!=0
float step_px = 0.0f;
float step_py = 0.0f;
float step_pz = 0.0f;


float step_rx = 0.0f;
float step_ry = 0.0f;
float step_rz = 0.0f;


// 根据距离、角度为xyz分别计算合适的步长:在start函数中算出
float standard_step_px = 0.0f;
float standard_step_py = 0.0f;
float standard_step_pz = 0.0f;


float standard_step_rx = 0.0f;
float standard_step_ry = 0.0f;
float standard_step_rz = 0.0f;
// 设置最小允许的误差,在将target和current进行比较时用==暂时就用2*步长替代吧


// Use this for initialization
void Start () {
cur_px = transform.position.x;
cur_py = transform.position.y;
cur_pz = transform.position.z;


cur_rx = transform.rotation.x;
cur_ry = transform.rotation.y;
cur_rz = transform.rotation.z;


standard_step_px = (target_px - cur_px) / frameCount;
standard_step_py = (target_py - cur_py) / frameCount;
standard_step_pz = (target_pz - cur_pz) / frameCount;


standard_step_rx = (target_rx - cur_rx) / frameCount;
standard_step_ry = (target_ry - cur_ry) / frameCount;
standard_step_rz = (target_rz - cur_rz) / frameCount;
}

// Update is called once per frame
void Update () {
// 移动
bool changed_p = false;
if (System.Math.Abs(target_px - cur_px) > System.Math.Abs(standard_step_px*2)) {
cur_px += standard_step_px;
step_px = standard_step_px;
changed_p = true;
}
if (System.Math.Abs(target_py - cur_py) > System.Math.Abs(standard_step_py*2)) {
cur_py += standard_step_py;
step_py = standard_step_py;
changed_p = true;
}
if (System.Math.Abs(target_pz - cur_pz) > System.Math.Abs(standard_step_pz*2)) {
cur_pz += standard_step_pz;
step_pz = standard_step_pz;
changed_p = true;
}
if (changed_p) {
this.transform.Translate (standard_step_px,standard_step_py,standard_step_pz);
}
// 旋转
bool changed_r = false;
if (System.Math.Abs(target_rx - cur_rx) > System.Math.Abs(standard_step_rx*2)) {
cur_rx += standard_step_rx;
step_rx = standard_step_rx;
changed_r = true;
}
if (System.Math.Abs(target_ry - cur_ry) > System.Math.Abs(standard_step_ry*2)) {
cur_ry += standard_step_ry;
step_ry = standard_step_ry;
changed_r = true;
}
if (System.Math.Abs(target_rz - cur_rz) > System.Math.Abs(standard_step_rz*2)) {
cur_rz += standard_step_rz;
step_rz = standard_step_rz;
changed_r = true;
}
if (changed_r) {
this.transform.Rotate (step_rx,step_ry,step_rz);
}
reset ();
}
// 将所有步长清零
void reset() {
step_px = 0.0f;
step_py = 0.0f;
step_pz = 0.0f;


step_rx = 0.0f;
step_ry = 0.0f;
step_rz = 0.0f;
}
}

你可能感兴趣的:(Unity摄像机 向指定位置移动旋转 C#脚本)