65 lines
2.0 KiB
C#
65 lines
2.0 KiB
C#
using UnityEngine;
|
|
using System.Collections;
|
|
|
|
public class CanvasController : MonoBehaviour
|
|
{
|
|
private CanvasGroup canvasGroup; // CanvasGroup do kontrolowania alfa Canvasu
|
|
public float displayDistance = 5f; // Odleg³oœæ, od której Canvas zaczyna siê pojawiaæ
|
|
public float fadeSpeed = 2f; // Prêdkoœæ wyœwietlania i zanikania Canvasu
|
|
|
|
private Transform player; // Referencja do transformacji gracza
|
|
private bool isPlayerClose = false;
|
|
|
|
void Start()
|
|
{
|
|
// ZnajdŸ obiekt gracza z tagiem "Player"
|
|
GameObject playerObject = GameObject.FindGameObjectWithTag("Player");
|
|
if (playerObject != null)
|
|
{
|
|
player = playerObject.transform;
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Player object not found! Make sure the player has the 'Player' tag.");
|
|
}
|
|
|
|
// ZnajdŸ CanvasGroup na tym samym obiekcie
|
|
canvasGroup = GetComponent<CanvasGroup>();
|
|
if (canvasGroup == null)
|
|
{
|
|
Debug.LogError("CanvasGroup component not found! Make sure the Canvas has a CanvasGroup component.");
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (player == null || canvasGroup == null)
|
|
return;
|
|
|
|
float distance = Vector3.Distance(transform.position, player.position);
|
|
|
|
// Sprawdzanie, czy gracz jest wystarczaj¹co blisko
|
|
if (distance <= displayDistance && !isPlayerClose)
|
|
{
|
|
isPlayerClose = true;
|
|
StopAllCoroutines();
|
|
StartCoroutine(FadeCanvas(1f)); // Poka¿ Canvas
|
|
}
|
|
else if (distance > displayDistance && isPlayerClose)
|
|
{
|
|
isPlayerClose = false;
|
|
StopAllCoroutines();
|
|
StartCoroutine(FadeCanvas(0f)); // Ukryj Canvas
|
|
}
|
|
}
|
|
|
|
private IEnumerator FadeCanvas(float targetAlpha)
|
|
{
|
|
while (!Mathf.Approximately(canvasGroup.alpha, targetAlpha))
|
|
{
|
|
canvasGroup.alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, fadeSpeed * Time.deltaTime);
|
|
yield return null;
|
|
}
|
|
}
|
|
}
|