1. 程式人生 > >Unity攝像機 向指定位置移動旋轉 C#指令碼

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