I am trying to simulate a Black Hole in the Galaxy, using a dedicated shader. The light coming behind the hole is modified going to the following effect.
A shader is applied on main camera, using the following script. The shader in included in the material myMat.
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (IsBlackHoleVisible)
Graphics.Blit(source, destination, myMat);
}
But some objects, that are in front of the black hole (blue ring) shall not be modified.
So I have created a second camera exactly at the same position and FOV than the Main Camera, but with depth starting at BlackHole position up to infinity.
The second camera is rendered in a target render texture. Then I want to copy part of this texture in a Sprite that is set at the BlockHole position.
I try the following script on Sprite object. But Sprite is blank or nothing…
public RenderTexture renderTexture;
public Texture2D texture2D;
public Vector2 blackholePos;
public Vector2 blackholeSize;
public SpriteRenderer mySprite;
// Start is called before the first frame update
void Start()
{
//Define texture2D
texture2D = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
//set SpriteRenderer
mySprite = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
//first method tested - copy renderTexture in texture2D
Graphics.CopyTexture(renderTexture, 0, 0, (int)blackholePos.x, (int)blackholePos.y, (int)blackholeSize.x, (int)blackholeSize.y, texture2D, 0, 0, 0, 0);
//second method tested - copy renderTexture in texture2D
RenderTexture.active = renderTexture;
texture2D.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
texture2D.Apply();
RenderTexture.active = null;
//then copy the texture2D as the Sprite
mySprite.sprite = Sprite.Create(texture2D, new Rect((int)blackholePos.x, (int)blackholePos.y, (int)blackholeSize.x, (int)blackholeSize.y), new Vector2(0, 0));
}
How to copy only part of a renderTexture in a Texture2D and apply it on a Sprite ?
Thanks for your help…