【Unity】初始化物体的旋转角度

需求:钟表的指针默认位置在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);
    }
}

实现物体围绕某一点进行旋转

http://blog.csdn.net/qiaoquan3/article/details/51306514


2017.05.07更新:

  • 嫌麻烦,还是用iTween和DoTween插件吧。
原文地址:https://www.cnblogs.com/guxin/p/unity-init-gameobject-transform-rotation.html