翻譯|使用教程|編輯:吉煒煒|2024-12-19 11:25:20.970|閱讀 144 次
概述:Unity 是一款功能極其豐富的游戲引擎,允許開(kāi)發(fā)人員將各種媒體集成到他們的項(xiàng)目中。但是,它缺少最令人興奮的功能之一 - 將 Web 內(nèi)容(例如 HTML、CSS 和 JavaScript)直接渲染到 3D 場(chǎng)景中的紋理上的能力。在本文中,我們將介紹如何使用 DotNetBrowser 在 Unity3D 中將 Web 內(nèi)容渲染為紋理。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門(mén)軟控件火熱銷(xiāo)售中 >>
Unity 是一款功能極其豐富的游戲引擎,允許開(kāi)發(fā)人員將各種媒體集成到他們的項(xiàng)目中。但是,它缺少最令人興奮的功能之一 - 將 Web 內(nèi)容(例如 HTML、CSS 和 JavaScript)直接渲染到 3D 場(chǎng)景中的紋理上的能力。這項(xiàng)技術(shù)為在 Unity 項(xiàng)目中創(chuàng)建動(dòng)態(tài)交互式元素提供了可能性,例如游戲內(nèi)瀏覽器、菜單、聊天、內(nèi)部 Wiki 或?qū)崟r(shí)數(shù)據(jù)顯示。
要在項(xiàng)目中實(shí)現(xiàn)此功能,您需要將 Web 視圖集成到 Unity 中。DotNetBrowser 是一個(gè)單獨(dú)的 .NET 庫(kù),用于加載和渲染網(wǎng)頁(yè),并支持 .NET Standard 2.0,因此可以集成到 Unity 中。
	 
 
在本文中,我們將介紹如何使用 DotNetBrowser 在 Unity3D 中將 Web 內(nèi)容渲染為紋理。
DotNetBrowser是一個(gè).NET庫(kù),允許將基于Chromium的WPF和WinForms組件嵌入到.NET應(yīng)用程序中,以顯示使用HTML5,CSS3,JavaScript,Silverlight等構(gòu)建的現(xiàn)代網(wǎng)頁(yè)。
	
 
	基于FPS Microgame模板的項(xiàng)目中HTML聊天和游戲菜單。
 
設(shè)置 Unity 項(xiàng)目
首先,確保您的 Unity 環(huán)境已設(shè)置并可供使用。打開(kāi) Unity Hub 并為 Windows、macOS 或 Linux 創(chuàng)建一個(gè)新的 3D 項(xiàng)目。
安裝 DotNetBrowser
要將 DotNetBrowser 依賴項(xiàng)作為包安裝,請(qǐng)執(zhí)行以下操作:
//github.com/TeamDev-IP/DotNetBrowser-Examples.git?path=csharp/unity3d/Dependencies
	 
 
安裝了 DotNetBrowser 依賴包的包管理器。
創(chuàng)建材質(zhì)來(lái)顯示網(wǎng)狀紋理
在將網(wǎng)頁(yè)內(nèi)容渲染到 3D 對(duì)象之前,您需要?jiǎng)?chuàng)建一種將網(wǎng)頁(yè)顯示為紋理的材質(zhì)。
 
	
將網(wǎng)頁(yè)內(nèi)容渲染為紋理
現(xiàn)在,您需要將網(wǎng)頁(yè)或 HTML 內(nèi)容渲染為可應(yīng)用于材質(zhì)的紋理。
using DotNetBrowser.Browser;
using DotNetBrowser.Browser.Widgets.Handlers;
using DotNetBrowser.Engine;
using DotNetBrowser.Geometry;
using DotNetBrowser.Handlers;
using DotNetBrowser.Ui;
using UnityEngine;
using Color = DotNetBrowser.Ui.Color;
namespace Assets.Scripts
{
    public class BrowserScript : MonoBehaviour
    {
        private Texture2D texture;
        // The URL to render.
        public string DefaultUrl = "http://html5test.teamdev.com";
        // The default browser width.
        public uint Width = 1024;
        // The default browser height.
        public uint Height = 768;
        // The latest rendered bitmap data of the browser web page.
        public Bitmap Bitmap { get; private set; }
        // An instance of IBrowser controlled by this script.
        public IBrowser Browser { get; private set; }
        // An instance of IEngine controlled by this script.
        public IEngine Engine { get; private set; }
        public void Awake()
        {
            // Initialize the DotNetBrowser engine.
            EngineOptions engineOptions = new EngineOptions.Builder
            {
                LicenseKey = "your_license_key",
                RenderingMode = RenderingMode.OffScreen
            }.Build();
            Engine = EngineFactory.Create(engineOptions);
            // Create a browser instance.
            Browser = Engine.CreateBrowser();
            // Set the browser size and transparency.
            Browser.Size = new Size(Width, Height);
            Browser.Settings.TransparentBackgroundEnabled = true;
            Browser.Settings.DefaultBackgroundColor =
                new Color(0, 0, 0, 0);
            // Configure rendering the browser content 
            // and save the rendered image.
            var provider = (IOffScreenRenderProvider)Browser;
            provider.PaintHandler = new Handler<PaintParameters>(p =>
                Bitmap = p.View);
            provider.Show();
        }
        public void OnDestroy() => Engine?.Dispose();
        public void Update()
        {
            if (Bitmap == null) return;
            int newWidth = (int)Bitmap.Size.Width;
            int newHeight = (int)Bitmap.Size.Height;
            if (texture == null || texture.width != newWidth
                || texture.height != newHeight)
            {
                texture = new Texture2D(newWidth, newHeight,
                    TextureFormat.BGRA32, true);
                var render = gameObject.GetComponent<MeshRenderer>();
                render.material.mainTexture = texture;
            }
            texture.SetPixelData((byte[])Bitmap.Pixels, 0);
            texture.Apply(true);
        }
        public void Start()
        {
            Browser.Navigation.LoadUrl(DefaultUrl);
        }
    }
}
分配腳本并測(cè)試
將腳本附加到您之前創(chuàng)建的平面。使用腳本和材質(zhì),您的平面的檢查器窗格應(yīng)如下所示:
 
在 Unity 中播放場(chǎng)景。現(xiàn)在應(yīng)該會(huì)在您應(yīng)用于平面的材質(zhì)上渲染網(wǎng)頁(yè)內(nèi)容。如果您已正確完成所有操作,則應(yīng)該看到以下內(nèi)容:
 
使網(wǎng)頁(yè)內(nèi)容具有交互性
您可以進(jìn)一步為網(wǎng)頁(yè)內(nèi)容添加交互性。例如,您可以讓用戶使用鼠標(biāo)或觸摸屏與網(wǎng)頁(yè)進(jìn)行交互。
您可能需要捕獲用戶點(diǎn)擊、鼠標(biāo)移動(dòng)或觸摸事件,以將其傳遞給 Web 內(nèi)容進(jìn)行交互。
在 Unity 中捕獲鼠標(biāo)點(diǎn)擊的最簡(jiǎn)單方法是將OnMouseDown() 和OnMouseUp()方法添加到BrowserScript:
// Get the current mouse point in browser coordinates.
private Point GetMousePoint()
{
    // Ensure the main camera exists on the scene.
    if (Camera.main != null)
    {
        // Create a ray from the camera's position 
        // through the current mouse position on the screen.
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        // Perform a raycast to detect collision 
        // with objects on the scene.
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            // Calculate the coordinates in the browser space.
            // Since "Tiling X" is -1, the X coordinate is inverted.
            int x = (int)(Width * (1 - hit.textureCoord.x));
            int y = (int)(Height * hit.textureCoord.y);
            return new Point(x, y);
        }
    }
    // Return null if no valid point could be calculated 
    // (e.g., no camera or no raycast hit).
    return null;
}
// OnMouseDown is called when the user presses the mouse button
// while over the collider.
public void OnMouseDown()
{
    var location = GetMousePoint();
    if (location == null) return;
    var args = new MousePressedEventArgs
    {
        Location = location,
        // OnMouseDown is called for the left clicks only.
        Button = MouseButton.Left, 
        ClickCount = 1
    };
    Browser.Mouse.Pressed.Raise(args);
}
public void OnMouseUp()
{
    var location = GetMousePoint();
    if (location == null) return;
    var args = new MouseReleasedEventArgs
    {
        Location = location,
        Button = MouseButton.Left,
        ClickCount = 1
    };
    Browser.Mouse.Released.Raise(args);
}
Unity 提供了許多用于捕獲用戶輸入的選項(xiàng),DotNetBrowser 擁有將鍵盤(pán)、觸摸和鼠標(biāo)事件傳遞到瀏覽器所需的所有 API。
優(yōu)化性能
在 Unity 中渲染 Web 內(nèi)容可能會(huì)占用大量資源。要優(yōu)化性能,請(qǐng)執(zhí)行以下操作:
結(jié)論
在 Unity3D 中將 Web 內(nèi)容渲染到紋理上,您可以創(chuàng)建游戲內(nèi)瀏覽器、基于 Web 的交互式儀表板,甚至是實(shí)時(shí)流式傳輸內(nèi)容。使用 DotNetBrowser 等庫(kù),將 Web 內(nèi)容直接集成到 Unity 項(xiàng)目中相對(duì)容易。按照以上步驟操作,您可以開(kāi)始嘗試不同的 Web 內(nèi)容,將其與 Unity 集成,并為交互式 3D 應(yīng)用程序開(kāi)辟新的可能性。
本指南為您提供了在 Unity 中將 Web 內(nèi)容顯示為紋理的堅(jiān)實(shí)基礎(chǔ)。無(wú)論您是在構(gòu)建虛擬現(xiàn)實(shí)項(xiàng)目、游戲還是交互式應(yīng)用程序,這些技術(shù)都可以顯著提升用戶體驗(yàn)。
產(chǎn)品試用下載、價(jià)格咨詢、優(yōu)惠獲取,或其他任何問(wèn)題,請(qǐng)聯(lián)系。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@ke049m.cn
文章轉(zhuǎn)載自:慧都網(wǎng)