_TheStrongestSnail/TheStrongestSnail/Assets/Scripts/Scene_main/sceneContorl.cs
2024-11-25 23:46:35 +08:00

110 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;
public class sceneContorl : MonoBehaviour
{
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值
// Start is called before the first frame update
void Start()
{
mainSceneRectTransform = mainScene.GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
#if UNITY_EDITOR || UNITY_STANDALONE
// 桌面端:鼠标按下时
if (Input.GetMouseButtonDown(0))
{
m_fingerDown = true;
m_oneFingerDragStartPos = Input.mousePosition; // 获取鼠标按下的起始位置
}
// 桌面端:鼠标松开时
if (Input.GetMouseButtonUp(0))
{
m_fingerDown = false;
}
// 处理鼠标拖动
if (m_fingerDown)
{
HandleFingerDragMove(Input.mousePosition);
}
#else
// 移动端:单指滑动
if (Input.touchCount == 1)
{
Touch touch = Input.touches[0];
// 手指刚触碰屏幕时
if (touch.phase == TouchPhase.Began)
{
m_fingerDown = true;
m_oneFingerDragStartPos = touch.position; // 获取手指按下的起始位置
}
// 手指在屏幕上滑动时
else if (touch.phase == TouchPhase.Moved)
{
HandleFingerDragMove(touch.position); // 处理手指拖动
}
}
else
{
m_fingerDown = false;
}
#endif
}
/// <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>
/// 屏幕坐标换算成3D坐标
/// </summary>
/// <param name="screenPos">屏幕坐标</param>
/// <returns></returns>
Vector3 GetWorldPos(Vector2 screenPos)
{
return m_cam.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, Mathf.Abs(m_cam.transform.position.z)));
}
}