_TheStrongestSnail/TheStrongestSnail/Assets/Scripts/Scene_main/sceneContorl.cs
2024-11-26 10:14:26 +08:00

100 lines
2.9 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.EventSystems;
public class sceneContorl : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
public Camera m_cam;
public GameObject mainScene;
private bool m_fingerDown = false;
// 手指的起始位置
private Vector2 m_oneFingerDragStartPos;
// UI元素的 RectTransform
private RectTransform mainSceneRectTransform;
// 灵敏度系数
private float sensitivity = 0.5f; // 可以根据需要调整此值
// 滑动限制的最小值和最大值
public float minX = -500f; // 最小x值
public float maxX = 500f; // 最大x值
[Header("定义目标位置")]
public float[] targetPositions = new float[] { 0f, -2100f, -3760f, -5350f };
// 引用 mainBTN 脚本
public mainBTN mainBtnScript;
// Start is called before the first frame update
void Start()
{
mainSceneRectTransform = mainScene.GetComponent<RectTransform>();
}
/// <summary>
/// 单指滑动
/// </summary>
private void HandleFingerDragMove(Vector2 fingerPos)
{
// 计算当前帧的滑动增量(交换顺序,保证滑动方向一致)
Vector3 moveDelta = fingerPos - m_oneFingerDragStartPos; // 当前触摸位置 - 起始位置
Vector3 newPos = mainSceneRectTransform.anchoredPosition;
// 根据滑动增量计算新的x轴位置并限制在指定范围内
newPos.x = newPos.x + (moveDelta.x * sensitivity);
// 限制x轴位置在 minX 和 maxX 之间
newPos.x = Mathf.Clamp(newPos.x, minX, maxX);
mainSceneRectTransform.anchoredPosition = newPos; // 设置新的锚点位置
// 更新起始位置,用于计算下一帧的增量
m_oneFingerDragStartPos = fingerPos;
}
/// <summary>
/// 计算当前位置与目标位置数组中哪个位置最接近,并返回对应的目标位置值.
/// </summary>
/// <param name="currentX">当前X坐标</param>
/// <returns>返回距离最近的目标位置值</returns>
float FindClosestNumber(float target)
{
float closestNumber = targetPositions[0]; // 默认第一个数为最近的数
float minDifference = Mathf.Abs(target - closestNumber); // 计算与第一个数的差值
foreach (float number in targetPositions)
{
float difference = Mathf.Abs(target - number); // 计算当前数与目标数的差值
if (difference < minDifference) // 如果当前差值更小,更新最近的数
{
closestNumber = number;
minDifference = difference;
}
}
return closestNumber;
}
public void OnDrag(PointerEventData eventData)
{
HandleFingerDragMove(eventData.position);
}
public void OnBeginDrag(PointerEventData eventData)
{
m_oneFingerDragStartPos = Input.mousePosition; // 获取鼠标按下的起始位置
}
public void OnEndDrag(PointerEventData eventData)
{
mainBtnScript.MovePanel(FindClosestNumber(mainSceneRectTransform.anchoredPosition.x));
}
}