Files
MRFishingMaster/Assets/_FishingMaster/Scripts/UI/PlayerUI.cs

170 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using DG.Tweening;
using DragonLi.Core;
using DragonLi.Frame;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
public class PlayerUI : MonoBehaviour
{
public TMP_Text timeTxt;
public TMP_Text coinTxt;
[NonSerialized]
public float second=60*15f;
public RectTransform[] hits;
public float fadeInDuration = 1.0f;
private CanvasGroup canvasGroup;
private int currentShowCoin;
private Tween coinTween;
public void Awake()
{
second = GameInit.Ins.gameTime;
}
void Start()
{
EventDispatcher.AddEventListener<int>("PlayerHit", ShowEx);
EventDispatcher.AddEventListener<int>("RefreshPlayerCoin", RefreshPlayerCoin);
canvasGroup = GetComponent<CanvasGroup>();
// 设置初始透明度为0
canvasGroup.alpha = 0f;
// 使用DoTween实现透明度从0到1的渐显效果
canvasGroup.DOFade(1f, fadeInDuration);
foreach (var item in hits)
{
item.gameObject.SetActive(false);
}
}
public void ShowEx(int txId)
{
if (hits == null || txId < 0 || txId >= hits.Length || hits[txId] == null)
{
Debug.LogError("特效索引无效或数组为空");
return;
}
// 激活特效
hits[txId].gameObject.SetActive(true);
GameManager.Ins.PlaySound2D("啃咬");
// 获取画布中心坐标
Vector3 canvasCenter = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, 0f);
// 简单偏移:上下左右随机方向偏移固定距离
Vector3 randomOffset = GetSimpleOffset();
// 设置UI位置
hits[txId].localPosition = randomOffset;
CoroutineTaskManager.Instance.WaitSecondTodo(() =>
{
if (hits[txId] != null)
{
hits[txId].gameObject.SetActive(false);
}
}, 2f);
}
public void RefreshPlayerCoin(int targetCoin)
{
// 如果有旧的 tween先停掉
if (coinTween != null && coinTween.IsActive())
coinTween.Kill();
int startCoin = currentShowCoin;
coinTween = DOTween.To(
() => startCoin,
value =>
{
startCoin = value;
currentShowCoin = value;
UpdateCoinText(value);
},
targetCoin,
0.5f // ⏱ 动画时长,可调
)
.SetEase(Ease.OutCubic);
}
void UpdateCoinText(int coin)
{
coinTxt.text = coin.ToString();
}
// 简单偏移:上下左右四个方向随机偏移
// 固定偏移量
private Vector3 GetSimpleOffset()
{
// 固定偏移200像素
float offset = 200f;
float offsetX = Random.Range(-offset, offset);
float offsetY = Random.Range(-100, offset);
return new Vector3(offsetX, offsetY, 0);
}
private void Update()
{
if (!GameManager.Ins.GameStart|| GameManager.Ins.isGameEnd) return;
if (second > 0)
{
second = second - Time.deltaTime;
if (second / 60 < 1)
{
if (second < 4)
{
}
timeTxt.text = string.Format("00:{0:d2}", (int)second % 60);
}
else
{
timeTxt.text = string.Format("{0:d2}:{1:d2}", (int)second / 60, (int)second % 60);
}
}
else
{
timeTxt.text = "00:00";
GameManager.Ins.WinEndGame();
}
}
}