我看你差不多了,但是你目前正在使用的是`Renderer`和`Material`,而不是`RenderTexture`和`Material`。
你需要使用`RenderTexture`。基本上,你需要先将视频渲染到`RenderTexture`中,然后将该纹理分配给两个球体的材质。
1.创建一个`RenderTexture`并将其分配给`VideoPlayer`。
2.为球体创建两个材质。
3.将`VideoPlayer.renderMode`设置为`VideoRenderMode.RenderTexture;`。
4.将两个球体的纹理设置为来自`RenderTexture`的纹理。
5.准备并播放视频。
下面的代码就是在做这件事情。它应该可以直接使用。你唯一需要做的事情就是根据你的需求修改每个材质的平铺和偏移。
你也应该注释掉:
leftSphere = createSphere("LeftEye", new Vector3(-5f, 0f, 0f), new Vector3(4f, 4f, 4f));
rightSphere = createSphere("RightEye", new Vector3(5f, 0f, 0f), new Vector3(4f, 4f, 4f));
接着使用从任何3D应用程序导入的球体。这行代码只是为了测试目的而存在,并且使用Unity的球体播放视频不是一个好主意,因为球体没有足够的细节来使视频变得平滑。
using UnityEngine;
using UnityEngine.Video;
public class StereoscopicVideoPlayer : MonoBehaviour
{
RenderTexture renderTexture;
Material leftSphereMat;
Material rightSphereMat;
public GameObject leftSphere;
public GameObject rightSphere;
private VideoPlayer videoPlayer;
private AudioSource audioSource;
void Start()
{
renderTexture = createRenderTexture();
leftSphereMat = createMaterial();
rightSphereMat = createMaterial();
leftSphere = createSphere("LeftEye", new Vector3(-5f, 0f, 0f), new Vector3(4f, 4f, 4f));
rightSphere = createSphere("RightEye", new Vector3(5f, 0f, 0f), new Vector3(4f, 4f, 4f));
leftSphere.GetComponent<MeshRenderer>().material = leftSphereMat;
rightSphere.GetComponent<MeshRenderer>().material = rightSphereMat;
videoPlayer = gameObject.AddComponent<VideoPlayer>();
audioSource = gameObject.AddComponent<AudioSource>();
videoPlayer.playOnAwake = false;
audioSource.playOnAwake = false;
videoPlayer.source = VideoSource.Url;
videoPlayer.url = "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
videoPlayer.renderMode = VideoRenderMode.RenderTexture;
videoPlayer.targetTexture = renderTexture;
assignTextureToSphere();
videoPlayer.Prepare();
videoPlayer.prepareCompleted += OnVideoPrepared;
}
RenderTexture createRenderTexture()
{
RenderTexture rd = new RenderTexture(1024, 1024, 16, RenderTextureFormat.ARGB32);
rd.Create();
return rd;
}
Material createMaterial()
{
return new Material(Shader.Find("Specular"));
}
void assignTextureToSphere()
{
leftSphereMat.mainTexture = renderTexture;
rightSphereMat.mainTexture = renderTexture;
}
GameObject createSphere(string name, Vector3 spherePos, Vector3 sphereScale)
{
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = spherePos;
sphere.transform.localScale = sphereScale;
sphere.name = name;
return sphere;
}
void OnVideoPrepared(VideoPlayer source)
{
Debug.Log("Done Preparing Video");
videoPlayer.Play();
audioSource.Play();
if (videoPlayer.canSetPlaybackSpeed)
{
videoPlayer.playbackSpeed = 1f;
}
}
}
还有一个Unity教程,介绍如何使用特殊着色器来实现此功能,但这对我和其他一些人不起作用。我建议您使用上述方法,直到VR支持被添加到VideoPlayer
API中。
VideoPlayer
仍然很新,处于beta阶段,并且仍然无法在某些Android设备上工作。Unity已经意识到了这个问题,并正在努力解决。请放心慢慢来。 - Programmer