Reputation: 11343
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class FadeScript : MonoBehaviour
{
public Camera camera;
public float fadeDuration = 5;
public bool alphaZero = false;
private Material material;
private float targetAlpha = 0;
private float lerpParam;
private float startAlpha = 1;
void Start()
{
Vector3 camFront = camera.transform.position + camera.transform.forward;
transform.position = camFront;
material = GetComponent<Renderer>().material;
SetMaterialAlpha(1);
}
void Update()
{
lerpParam += Time.deltaTime;
float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
SetMaterialAlpha(alpha);
if (alpha == 0)
{
alphaZero = true;
}
}
public void FadeTo(float alpha, float duration)
{
startAlpha = material.color.a;
targetAlpha = alpha;
fadeDuration = duration;
lerpParam = 0;
}
private void SetMaterialAlpha(float alpha)
{
Color color = material.color;
color.a = alpha;
material.color = color;
}
}
I want that the transform will be in front of the camera. So I did in the Start:
Vector3 camFront = camera.transform.position + camera.transform.forward;
transform.position = camFront;
In this case transform is a Plane. The script is attached to the Plane.
But the result is that the Plane is not covering the whole camera view. I want to make a whole black view and then it will fade out. The fading is working fine bu the plane position is not fine:
On the bottom is the game view window while the game is running. This is a bit after the fading started and you can see that the plane is not covering the whole camera. On the right there is a space.
Maybe i need somehow to change the plane size and rotation too ? The idea is to position the plane in front the camera automatic to make it all black.
Upvotes: 1
Views: 1360
Reputation: 4110
If the camera can move, you also need to set the same orientation to your plane
transform.rotation = camera.transform.rotation;
Then simply make the plane really big will work (use the scale param). Of course you could also compute the exact size if needs to have but it is not that trivial with a perspective camera.
Another solution, as suggested by m.rogalski in a comment on your post, is to use a canvas that fills the screen:
Create an empty object on your scene and add the Canvas component to it.
In RenderMode choose Screen Space - Overlay
Create another gameobject below it in the hierarchy
On this gameObject, add the Image Component, put a black image, or no image and a black color
On this same component, set the anchors of the transform to be from 0 to 1, and no position offset, to cover the whole screen
Upvotes: 3