需求:鍾表的指針默認位置在0點,在初始化時會根據當前的時間,旋轉到一定角度。然后才是在當前旋轉角度下每幀繼續旋轉。
問題:網上搜到的關於物體的旋轉,基本都是給定一個速度的持續運動,而現在需要的是一個即時的效果。
看一看文檔:https://docs.unity3d.com/ScriptReference/Transform.Rotate.html
其實還是使用Transform.Rotate,但是文檔中的所有案例都是給定速度的持續運動,因為這個過程寫在了Update()中,會每幀被調用,所以傳參Time.deltaTime都是在指定每秒鍾旋轉的角度。
其實這里可以直接寫在Start()里面,只在初始化時執行一次,傳參為我們想要的角度,即可實現初始化就立即旋轉到指定角度。
分針的運動腳本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 分針繞着軸心旋轉的動畫
/// </summary>
public class MPRotateAnim : MonoBehaviour {
public GameObject axesObj; // 軸心物體
private float speed = 6; // 旋轉速度,6度/分鍾。
private float loop = 60; // 用於計算轉一圈的角度。時針為24,分針秒針為60。
// Use this for initialization
void Start () {
// 初始化當前指針的位置和角度
DateTime now = DateTime.Now;
float degree = now.Minute / loop * 360;
Debug.Log("MPdegree = " + degree);
gameObject.transform.Rotate(0, 0, -degree, Space.Self);
Debug.Log("gameObject.transform.rotation = " + gameObject.transform.rotation);
}
// Update is called once per frame
void Update () {
gameObject.transform.RotateAround(axesObj.transform.position, -Vector3.forward, speed / 60 * Time.deltaTime);
}
}
時針的運動腳本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 時針繞着軸心旋轉的動畫
/// </summary>
public class HPRotateAnim : MonoBehaviour {
public GameObject axesObj; // 軸心物體
private float speed = 30; // 旋轉速度,30度/小時。
private float loop = 24; // 用於計算轉一圈的角度。時針為24,分針秒針為60。
// Use this for initialization
void Start () {
// 初始化當前指針的位置和角度
DateTime now = DateTime.Now;
float degree = (now.Hour * 60 + now.Minute) / (loop * 60) * 360;
Debug.Log("HPdegree = " + degree);
gameObject.transform.Rotate(0, 0, -degree, Space.Self);
Debug.Log("gameObject.transform.rotation = " + gameObject.transform.rotation);
}
// Update is called once per frame
void Update () {
gameObject.transform.RotateAround(axesObj.transform.position, -Vector3.forward, speed / (60 * 60) * Time.deltaTime);
}
}
另外一些關於旋轉的常見問題
根據輸入每幀進行旋轉、平移
public class ExampleClass : MonoBehaviour {
public float speed = 10.0F;
public float rotationSpeed = 100.0F;
void Update() {
float translation = Input.GetAxis("Vertical") * speed;
float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
translation *= Time.deltaTime;
rotation *= Time.deltaTime;
transform.Translate(0, 0, translation);
transform.Rotate(0, rotation, 0);
}
}
實現物體圍繞某一點進行旋轉
2017.05.07更新:
- 嫌麻煩,還是用iTween和DoTween插件吧。