在場景中新建一個Rotate的腳本,並把這個腳本掛載到我們要進行旋轉的遊戲物體上,然後雙擊打開該腳本,並複製一下的代碼!!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotate : MonoBehaviour {
private Transform go;
void Start()
{
go = GetComponent<Transform>();
}
void Update()
{
//插值旋轉 非勻速轉向target的位置。(人物運動看起來比較合理)
go.rotation = Quaternion.Slerp(go.rotation, Quaternion.Euler(new Vector3(0, -90, 0)) , Time.deltaTime);
//勻速轉向target的位置。(比較生硬)
//go.rotation = Quaternion.RotateTowards(go.rotation, Quaternion.Euler(new Vector3(0, -90, 0)) , Time.deltaTime * 30);
//當初始值跟目標角度小於2,就將目標角度賦值給初始角度,讓旋轉角度是我們需要的角度
if (Quaternion.Angle(go.rotation, Quaternion.Euler(new Vector3(0, -90, 0)) < 2)
{
go.rotation = Quaternion.Euler(new Vector3(0, -90, 0);
}
}
}
然後保存該腳本,在這裏我是採用了兩種方式讓物體旋轉到我們指定的Vector3的值,在這裏旋轉到的值爲(0,-90,0),第二種方式也就是勻速轉向在代碼中被我給註釋掉了,如果有需要的朋友可以取消註釋!!!