代码
代码片
RequireComponent(typeof(Camera))]
public class CameraController : MonoBehaviour
{
private Camera _camera;
bool _fingerDown = false;
Vector3 _oneFingerDragStartPos;
float _twoFingerLastDistance = -1;
[SerializeField] Vector2 _minPosition;
[SerializeField] Vector2 _maxPosition;
[SerializeField] float _defaultSize = 5f;
[SerializeField] float _minSize;
[SerializeField] float _maxSize;
[SerializeField] float _scaleSpeed = 0.1f;
[SerializeField] float _moveSpeed = 1f;
Vector3 _lockPosition;
public Vector3 LockPosition { get => ChangePosition(_lockPosition); set => _lockPosition = value; }
private void Awake()
{
_camera = GetComponent<Camera>();
}
private void Update()
{
#if UNITY_EDITOR
MouseControl();
#else
TouchControl();
#endif
}
void MouseControl()
{
if (Input.GetMouseButtonDown(0))
{
_fingerDown = true;
_oneFingerDragStartPos = GetWorldPosition(Input.mousePosition);
}
if (Input.GetMouseButtonUp(0))
{
_fingerDown = false;
_twoFingerLastDistance = -1;
}
if (_fingerDown)
{
HandleFingerDragMove(Input.mousePosition);
}
var distance = Input.GetAxis("Mouse ScrollWheel");
HandleMouseScrollWheel(distance * 10);
}
void TouchControl()
{
if (Input.touchCount == 2)
{
HandleTwoFingerScale();
}
else if (Input.touchCount == 1)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
_fingerDown = true;
_oneFingerDragStartPos = GetWorldPosition(Input.mousePosition);
}
else if (Input.touches[0].phase == TouchPhase.Moved)
{
HandleFingerDragMove(Input.touches[0].position);
}
_twoFingerLastDistance = -1;
}
else
{
_fingerDown = false;
_twoFingerLastDistance = -1;
}
}
private void HandleFingerDragMove(Vector2 fingerPos)
{
Vector3 disance = _oneFingerDragStartPos - GetWorldPosition(fingerPos);
Vector3 newPos = _camera.transform.position;
newPos += disance;
newPos.Set(Mathf.Clamp(newPos.x, _minPosition.x, _maxPosition.x), Mathf.Clamp(newPos.y, _minPosition.y, _maxPosition.y), -10);
_camera.transform.position = newPos;
}
private void HandleTwoFingerScale()
{
float distance = Vector2.Distance(Input.touches[0].position, Input.touches[1].position);
if (_twoFingerLastDistance == -1)
{
_twoFingerLastDistance = distance;
}
float scale = _scaleSpeed * (distance - _twoFingerLastDistance);
ScaleCamere(scale);
_twoFingerLastDistance = distance;
}
private void HandleMouseScrollWheel(float distance)
{
if (distance == 0) return;
ScaleCamere(distance);
}
private void ScaleCamere(float scale)
{
_camera.orthographicSize = Mathf.Clamp(_camera.orthographicSize - scale * _scaleSpeed, _minSize, _maxSize);
}
Vector3 GetWorldPosition(Vector2 screenPos)
{
return _camera.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, 0));
}
Vector3 ChangePosition(Vector3 worldPositon)
{
worldPositon.x = -10;
return worldPositon;
}
public void M_BackRS()
{
_camera.transform.position = _lockPosition;
_camera.orthographicSize = _defaultSize;
}
public void M_CameraFocusing(Vector3 center)
{
_camera.transform.position.Set(center.x, center.y, -10f);
}
}
|