Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Unity Sprite on front of camera
public class TestExecutor : MonoBehaviour
{
private Texture2D blackTexture;
private SpriteRenderer testSprite;
void Start()
{
// Create black texture
blackTexture = new Texture2D(32, 32, TextureFormat.RGB24, false);
blackTexture.SetPixel(0, 0, Color.white);
blackTexture.Apply();
// Create Sprite
var sprite = Sprite.Create(
texture: blackTexture,
rect: new Rect(0, 0, blackTexture.width, blackTexture.height),
pivot: new Vector2(0.5f, 0.5f)
);
// Create Sprite from script
testSprite = new GameObject("TestSprite").AddComponent<SpriteRenderer>();
testSprite.sprite = sprite;
}
void Update()
{
var distance = 10f;
// https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html
// calc world screen size, depens on distance from camera
// (distance +1f) , it is covered screen
var worldScreenH = 2.0f * (distance + 1f) * Mathf.Tan(Camera.main.fieldOfView * 0.5f * Mathf.Deg2Rad);
var worldScreenW = worldScreenH * Camera.main.aspect;
// fixed Sprite size
testSprite.transform.localScale = new Vector3(worldScreenW / testSprite.sprite.bounds.size.x, worldScreenH / testSprite.sprite.bounds.size.y);
// copy position and rotation, forward vector is very convenient
testSprite.transform.position = Camera.main.transform.position + testSprite.transform.forward.normalized * distance;
testSprite.transform.rotation = Camera.main.transform.rotation;
// when you fading
testSprite.color = new Color(0, 0, 0, fadingAlpha);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment