網頁

2018年7月20日 星期五

HoloLens 的 Sharing 功能 (程式碼解說)

本文將仔細介紹微軟網站所提供的 MR Sharing 240: Multiple HoloLens devices [前往]。
我就不仔細翻譯網站所提供的文件,此處我只想做個紀錄,主要是關於程式碼的部分。

目標:我想要用聲控說「play」,讓animator開始執行動作。
            animator 已經事先寫好animator controller,並且指定好條件設定。
            我想讓兩台HoloLens之間,可以同步執行上述這件事情。



Step1:想辦法用語音聲控,事件驅動以下的一系列程序。 

HologramPlacements.cs
---------聲控的設定 (恕刪)-------------
//寫一段事件驅動的程式碼,讓他一旦偵測到聲音說play,就執行以下function。
playAction();
----------------------------------------------
public void playAction()
    {
        GetComponent<Animator>().SetTrigger("Action_1");
        GetComponent<Animator>().speed = 1;

        CustomMessages.Instance.SendplayAction(); //傳遞訊息給其他HoloLens
    }

Step2: 在CustomMessages.cs 寫入SendplayAction()

這裡有兩件事要做,第一件事是宣告playAction,第二件事是寫SendplayAction()

CustomMessages.cs

1. 宣告playAction
public enum TestMessageID : byte
    {
        HeadTransform = MessageID.UserMessageIDStart,
        UserAvatar,
        UserHit,
        ShootProjectile,
        StageTransform,
        ResetStage,
        playAction, //這個項目要自己設定進去
        stopAction,
        ExplodeTarget,
        Max
    }

2. 寫SendplayAction()
public void SendplayAction()
    {
        // If we are connected to a session, broadcast our head info
        if (this.serverConnection != null && this.serverConnection.IsConnected())
        {
            // Create an outgoing network message to contain all the info we want to send
            NetworkOutMessage msg = CreateMessage((byte)TestMessageID.playAction); //記得改成你新增的項目
         
            // Send the message as a broadcast, which will cause the server to forward it to all other users in the session.
            this.serverConnection.Broadcast(
                msg,
                MessagePriority.Immediate ,
                MessageReliability.ReliableOrdered,
                MessageChannel.Avatar);
        }
    }

照理講,寫到這裡就可以傳送message出去,等待另一台HoloLens接收到message。

Step 3: 負責接收message

HologramPlacements.cs
void Start()
{
CustomMessages.Instance.MessageHandlers[CustomMessages.TestMessageID.playAction] = this.OnPlayAction;
}

負責聆聽是否有playAction的message,一旦收到就做跟第一台HoloLens一樣的事情。

Step 4: 那件事就是播放animation。

(ps.此處就不需要再次送message了,以免進入無窮傳遞。)

HologramPlacements.cs
void OnPlayAction(NetworkInMessage msg)
    {
        GetComponent<Animator>().SetTrigger("Action_1");
        GetComponent<Animator>().speed = 1;
    }

很簡單吧!

這篇論壇 [前往]寫得很好,也可以參考這群很厲害的人的討論。

沒有留言:

張貼留言