_TheStrongestSnail/TheStrongestSnail/Assets/Scripts/Scene_main/mainBTN.cs
2024-11-26 15:33:45 +08:00

86 lines
2.5 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 System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
//MD FUCK Everthing
//史山,别学
public class mainBTN : MonoBehaviour
{
public GameObject mainPanel;
private RectTransform mainPanelRect;
public GameObject BTN_0;
public GameObject BTN_1;
public GameObject BTN_2;
public GameObject BTN_3;
public GameObject BTN_0_0;
public GameObject BTN_1_1;
public GameObject BTN_2_2;
public GameObject BTN_3_3;
// Start is called before the first frame update
void Start()
{
// 确保mainPanel不为空
if (mainPanel == null)
{
Debug.LogError("mainPanel is not assigned!");
return;
}
mainPanelRect = mainPanel.GetComponent<RectTransform>();
// 添加按钮点击事件
BTN_0.GetComponent<Button>().onClick.AddListener(() => MovePanel(0));
BTN_1.GetComponent<Button>().onClick.AddListener(() => MovePanel(-2100));
BTN_2.GetComponent<Button>().onClick.AddListener(() => MovePanel(-3760));
BTN_3.GetComponent<Button>().onClick.AddListener(() => MovePanel(-5350));
}
// 统一的面板移动方法
public void MovePanel(float targetX)
{
// 更新按钮的显示和隐藏
BTN_0.SetActive(targetX != 0);
BTN_1.SetActive(targetX != -2100);
BTN_2.SetActive(targetX != -3760);
BTN_3.SetActive(targetX != -5350);
BTN_0_0.SetActive(targetX == 0);
BTN_1_1.SetActive(targetX == -2100);
BTN_2_2.SetActive(targetX == -3760);
BTN_3_3.SetActive(targetX == -5350);
// 使用 DOTween 实现平滑移动
mainPanelRect.DOKill(); // 杀死之前的动画,防止重复动画干扰
mainPanelRect.DOAnchorPosX(targetX, 0.3f).SetEase(Ease.Linear);
}
//协程实现平滑移动
//web端协程消耗特别大尽量不用
private IEnumerator SmoothMovePanel(float targetX, float duration)
{
Vector2 startPosition = mainPanelRect.anchoredPosition;
Vector2 targetPosition = new Vector2(targetX, startPosition.y);
float elapsedTime = 0f;
while (elapsedTime < duration)
{
// 计算当前进度
float t = elapsedTime / duration;
// 逐渐改变 position
mainPanelRect.anchoredPosition = Vector2.Lerp(startPosition, targetPosition, t);
// 增加时间
elapsedTime += Time.deltaTime;
yield return null;
}
// 最终确保位置为目标位置
mainPanelRect.anchoredPosition = targetPosition;
}
}