unity+時間戳的應用

WalkingSnail發表於2024-03-16

時間戳場景:報一串數字,當聽到數字“1”敲一下桌子,需要將敲桌子的時間戳與開始讀語音的時間戳的差值給到服務端。後端實現唸到數字1時,ui有閃動的效果

程式碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class MOCAOperation11 : MonoBehaviour
{

   
    /// <summary>
    /// 敲擊桌子時間點
    /// </summary>
    public string CurrentStrikeTimePoint;
    /// <summary>
    /// 起始位置時間戳毫秒
    /// </summary>
    long StartTimestamp;
    /// <summary>
    /// 當前時間戳(毫秒)
    /// </summary>
    long currentTimestamp;
    long currentSubMilliSeconds;
    // Start is called before the first frame update
    void Start()
    {
        AudioPlayRecord.Instance.PlayAudio(MOCASceneModelManage.Instance.audio_Title);
       

        ////獲取當前時間戳
        //long unixTime = ConvertDateTimep(DateTime.Now);
        //Debug.Log(unixTime);
        //將時間戳轉換為DateTime
        //Debug.Log(GetTime(unixTime.ToString()).ToString());
        StartTimestamp = GetTime();
        //Debug.Log("初始時間戳毫秒"+ StartTimestamp);

        //Debug.Log(GetTime(unixTime.ToString()).Year);
        //Debug.Log(GetTime(unixTime.ToString()).Month);
        //Debug.Log(GetTime(unixTime.ToString()).Day);
        //Debug.Log(GetTime(unixTime.ToString()).Hour);
        //Debug.Log(GetTime(unixTime.ToString()).Minute);
        //Debug.Log(GetTime(unixTime.ToString()).Second);

    }
    /// <summary>
    /// 獲取時間戳(精確到秒)
    /// TimeTool.ConvertDateTimep(DateTime.Now)
    /// </summary>
    /// <param name="time">時間</param>
    public static long ConvertDateTimep(DateTime time)
    {
        return ((time.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
        //等價於:
        //return ((time.ToUniversalTime().Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks) / 10000000) * 1000;
    }
    /// <summary>
    /// 獲得時間戳 (毫秒)
    /// </summary>
    /// <returns></returns>
    private long GetTime()
    {
        //精確到毫秒
        //return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
        return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();

    }
    /// <summary>
    /// 時間戳轉為C#格式時間
    /// TimeTool.GetTime(TimeTool.ConvertDateTiemp(DateTime.Now).ToString())
    /// </summary>
    /// <param name="timeStamp">時間戳</param>
    /// <returns></returns>
    public static DateTime GetTime(string timeStamp)
    {
        if (timeStamp.Length > 10)
        {
            timeStamp = timeStamp.Substring(0, 10);
        }
        DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dateTimeStart.Add(toNow);
    }


    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            ClickTable();

        }

        if (Input.GetKeyDown(KeyCode.U))
        {
            Debug.LogError("敲擊桌子MOCALeftTable:");
            ClickTable();

        }
        if (Input.GetKeyDown(KeyCode.I))
        {
            Debug.LogError("敲擊桌子MOCARightTable:");
            ClickTable();

        }
    }
    /// <summary>
    /// 敲桌子效果,以及記錄時間戳差值
    /// </summary>
    private void ClickTable()
    {
        //獲取當前時間,並列印當前時間與開始時間相差秒數(以秒為單位)
        MOCASceneModelManage.Instance.PlayAudio(MOCASceneModelManage.Instance.audio_Effect);

        //DateTime curtimer = DateTime.Now;
        //Debug.Log(curtimer);
        //int timer = GetSubSeconds(startTime, curtimer);
        //Debug.Log(timer);
        //Debug.LogError("敲擊桌子MOCALeftTable:" + timer);
        currentTimestamp = GetTime();
        //Debug.Log("當前時間戳毫秒" + currentTimestamp);

        currentSubMilliSeconds = GetSubMilliSeconds(StartTimestamp, currentTimestamp);
        //Debug.LogError("時間戳差值:"+ currentSubMilliSeconds);
        CurrentStrikeTimePoint += currentSubMilliSeconds + ",";
        CurrentStrikeTimePoint.TrimEnd(',');//末尾有多個逗號,會全部刪除.

        //Debug.LogError("時間戳差值str CurrentStrikeTimePoint:" + CurrentStrikeTimePoint);
    }

    private void OnCollisionEnter(Collision collision)
    {
        Debug.LogError(collision.gameObject.name);
        switch (collision.gameObject.name)
        {
            case "MOCALeftTable":
                Debug.LogError("敲擊桌子MOCALeftTable Enter:" );
                ClickTable();


                //AddUserAnswers(InteractionState.Place);
                break;
            case "MOCARightTable":
                Debug.LogError("敲擊桌子MOCARightTable Enter:" );
                ClickTable();

                break;
            default:
                break;
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        switch (collision.gameObject.name)
        {
            case "MOCALeftTable":
                Debug.LogError("MOCALeftTable Exit");
                MOCASceneModelManage.Instance.StopAudio();

                //AddUserAnswers(InteractionState.Place);
                break;
            case "MOCARightTable":
                Debug.LogError("MOCARightTable Exit");
                MOCASceneModelManage.Instance.StopAudio();

                break;
            default:
                break;
        }
    }

    /// <summary>
    /// 獲取間隔毫秒數
    /// </summary>
    /// <param name="startTimer"></param>
    /// <param name="endTimer"></param>
    /// <returns></returns>
    public long GetSubMilliSeconds(long startTimer, long endTimer)
    {
        //TimeSpan startSpan = new TimeSpan(startTimer);

        //TimeSpan nowSpan = new TimeSpan(endTimer);

        //TimeSpan subTimer = nowSpan.Subtract(startSpan).Duration();
        //Debug.LogError("startSpan:"+ startSpan+ "nowSpan:"+ nowSpan+ "subTimer:"+ subTimer);
        ////返回間隔秒數(不算差的分鐘和小時等,僅返回秒與秒之間的差)
        ////return subTimer.Seconds;

        ////返回相差時長(算上分、時的差值,返回相差的總毫秒秒數)
        //return (long)subTimer.TotalMilliseconds;
        return endTimer - startTimer;
    }

    /// <summary>
    /// 獲取間隔秒數
    /// </summary>
    /// <param name="startTimer"></param>
    /// <param name="endTimer"></param>
    /// <returns></returns>
    public int GetSubSeconds(DateTime startTimer, DateTime endTimer)
    {
        TimeSpan startSpan = new TimeSpan(startTimer.Ticks);

        TimeSpan nowSpan = new TimeSpan(endTimer.Ticks);

        TimeSpan subTimer = nowSpan.Subtract(startSpan).Duration();

        //返回間隔秒數(不算差的分鐘和小時等,僅返回秒與秒之間的差)
        //return subTimer.Seconds;

        //返回相差時長(算上分、時的差值,返回相差的總秒數)
        return (int)subTimer.TotalSeconds;
    }

    /// <summary>
    /// 獲取兩個時間的相差多少分鐘
    /// </summary>
    /// <param name="startTimer"></param>
    /// <param name="endTimer"></param>
    /// <returns></returns>
    public int GetSubMinutes(DateTime startTimer, DateTime endTimer)
    {
        TimeSpan startSpan = new TimeSpan(startTimer.Ticks);

        TimeSpan nowSpan = new TimeSpan(endTimer.Ticks);

        TimeSpan subTimer = nowSpan.Subtract(startSpan).Duration();

        //返回相差時長(僅返回相差的分鐘數)
        //return subTimer.Minutes;
        //返回相差時長(僅返回相差的總分鐘數)
        return (int)subTimer.TotalMinutes;
    }


    /// <summary>
    /// 獲取兩個時間的相差多少小時
    /// </summary>
    /// <param name="startTimer"></param>
    /// <param name="endTimer"></param>
    /// <returns></returns>
    public int GetSubHours(DateTime startTimer, DateTime endTimer)
    {
        TimeSpan startSpan = new TimeSpan(startTimer.Ticks);

        TimeSpan nowSpan = new TimeSpan(endTimer.Ticks);

        TimeSpan subTimer = nowSpan.Subtract(startSpan).Duration();

        //返回相差時長(僅返回相差的小時)
        //return subTimer.Hours;
        //返回相差時長(返回相差的總小時數)
        return (int)subTimer.TotalHours;
    }

    /// <summary>
    /// 獲取兩個時間的相差多少天
    /// </summary>
    /// <param name="startTimer"></param>
    /// <param name="endTimer"></param>
    /// <returns></returns>
    public int GetSubDays(DateTime startTimer, DateTime endTimer)
    {
        TimeSpan startSpan = new TimeSpan(startTimer.Ticks);

        TimeSpan nowSpan = new TimeSpan(endTimer.Ticks);

        TimeSpan subTimer = nowSpan.Subtract(startSpan).Duration();

        //返回相差時長(僅返回相差的天數)
        //return subTimer.Days;
        //返回相差時長(返回相差的總天數)
        return (int)subTimer.TotalDays;
    }


}

相關文章