萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

Unity3D 遊戲影片播放雙解:MovieTexture 平面投射與 GUI 全螢幕繪製

支援格式與匯入

Unity 原生支援 .mov、.mpg、.mpeg、.mp4、.avi、.asf。將影片拖入 Project 視窗,自動生成 MovieTexture 資產;若含音訊,同步產生 AudioClip。

方法一:平面投射法

1. 場景佈置

  • 建立 Plane 作為投影平面
  • 加入 Directional Light 照亮場景
  • 調整 Main Camera 正對平面

2. 控制腳本

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
    public MovieTexture movTexture;

    void Start() {
        GetComponent<Renderer>().material.mainTexture = movTexture;
        movTexture.loop = true;
    }

    void OnGUI() {
        if(GUILayout.Button("播放/繼續")) {
            if(!movTexture.isPlaying) movTexture.Play();
        }
        if(GUILayout.Button("暫停播放")) movTexture.Pause();
        if(GUILayout.Button("停止播放")) movTexture.Stop();
    }
}

將腳本掛載於 Plane,Inspector 中指定 MovieTexture。運行後透過按鈕控制播放狀態。

3. 運行時動態縮放

transform.localScale = new Vector3(2, 2, 1); // X/Y/Z 縮放係數

調整 Plane 的 localScale 即可同步改變影片顯示大小。

方法二:GUI 全螢幕繪製法

刪除 Plane 與燈光,將腳本改掛載於 Main Camera,修改 OnGUI:

void OnGUI() {
    // 以螢幕解析度繪製,拉伸填滿
    GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), movTexture, ScaleMode.StretchToFill);

    if(GUILayout.Button("播放/繼續")) { if(!movTexture.isPlaying) movTexture.Play(); }
    if(GUILayout.Button("暫停播放")) movTexture.Pause();
    if(GUILayout.Button("停止播放")) movTexture.Stop();
}

原理:直接呼叫 GUI.DrawTexture 將影片貼圖繪製於螢幕矩形區域。修改 Rect 參數即可動態調整顯示區域與大小。

兩種方式比較

維度平面投射法GUI 繪製法
適用場景場景內電視、投影幕、監視器畫面全螢幕過場動畫、啟動畫面、UI 埋入影片
3D 空間關係受光照、陰影、遮擋影響疊加於 UI 層,不受 3D 空間影響
效能需渲染幾何體,稍高直接繪製,較輕量
互動性可射線偵測點擊需自行處理座標轉換

結語

Unity 的 MovieTexture 提供了直觀的影片播放 API。平面投射法適合沉浸式場景內嵌影片;GUI 繪製法則適合全螢幕或 UI 整合播放。根據專案需求選擇,即可輕鬆實現影片播放功能。

copyright © 萬盛學電腦網 all rights reserved