我可以制作2D镜子吗

我可以制作2D镜子吗

本文介绍了Unity-我可以制作2D镜子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作自上而下的基于图块的2D游戏。在这个游戏中,我想将一堵墙变成一面镜子,就像您在,然后将 Texture2D 转换为 Sprite , a href = https://docs.unity3d.com/ScriptReference/Sprite.Create.html rel = nofollow noreferrer> Sprite.Create 函数。

It is possible to convert RenderTexture to a Sprite. First of all, convert the RenderTexture to Texture2D then convert the Texture2D to Sprite with the Sprite.Create function.

最好禁用第二个或镜像相机,然后使用 mirrorCam.Render()仅手动渲染它在需要的时候。以下脚本可以帮助您入门。将其附加到一个空的GameObject上,然后从编辑器中分配镜像相机和目标 SpriteRenderer ,它应该将相机看到的内容镜像到 SpriteRenderer 。不要忘记将 RenderTexture 插入镜像相机。

It is better to disable the second or mirror camera then use mirrorCam.Render() to manually render it only when you need to. The script below should get you started. Attach it to an empty GameObject then assign the mirror camera and the target SpriteRenderer from the Editor and it should mirror the what the camera is seeing to the SpriteRenderer. Don't forget to plugin RenderTexture to the mirror camera.

public class CameraToSpriteMirror: MonoBehaviour
{
    public SpriteRenderer spriteToUpdate;
    public Camera mirrorCam;

    void Start()
    {
        StartCoroutine(waitForCam());
    }

    WaitForEndOfFrame endOfFrame = new WaitForEndOfFrame();

    IEnumerator waitForCam()
    {
        //Will run forever in this while loop
        while (true)
        {
            //Wait for end of frame
            yield return endOfFrame;

            //Get camera render texture
            RenderTexture rendText = RenderTexture.active;
            RenderTexture.active = mirrorCam.targetTexture;

            //Render that camera
            mirrorCam.Render();

            //Convert to Texture2D
            Texture2D text = renderTextureToTexture2D(mirrorCam.targetTexture);

            RenderTexture.active = rendText;

            //Convert to Sprite
            Sprite sprite = texture2DToSprite(text);

            //Apply to SpriteRenderer
            spriteToUpdate.sprite = sprite;

        }
    }

    Texture2D renderTextureToTexture2D(RenderTexture rTex)
    {
        Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGB24, false);
        tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
        tex.Apply();
        return tex;
    }

    Sprite texture2DToSprite(Texture2D text2D)
    {
        Sprite sprite = Sprite.Create(text2D, new Rect(0, 0, text2D.width, text2D.height), Vector2.zero);
        return sprite;
    }
}

这篇关于Unity-我可以制作2D镜子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:32