unity中 限定UI的移动范围
前言:在最近项目中需要做一个功能,对image可进行放大缩小,移动,放大缩小,移动都比较简单,难点在于限定image的移动范围
//image控件四个角的点坐标
Vector3[] m_corners = new Vector3[4];
void CamereControl() { Camera camera = Camera.main.GetComponent<Camera>(); if (camera) { if (!camera.pixelRect.Contains(Input.mousePosition)) { return; } } m_bookImageRect.localScale = new Vector3(Mathf.Clamp(m_bookImageRect.localScale.x + Input.GetAxis("Mouse ScrollWheel"), 1, 5), Mathf.Clamp(m_bookImageRect.localScale.y + Input.GetAxis("Mouse ScrollWheel"), 1, 5), m_bookImageRect.localScale.z); if (Input.GetMouseButtonUp(1)) { Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto); } if (Input.GetMouseButton(1)) { Cursor.SetCursor(m_cursorTexture, new Vector2(16,16), CursorMode.Auto); float m_x = Input.GetAxis("Mouse X"); float m_y = Input.GetAxis("Mouse Y"); Vector3 m_moveOffset = new Vector3(m_x, m_y, 0); Vector3 m_tempPos = m_bookImageRect.position; m_bookImageRect.position += m_moveOffset * Time.deltaTime * m_keySpeed * m_bookImageRect.localScale.x; m_customBook.GetWorldCorners(m_corners); if (m_corners[0].x > Screen.currentResolution.width - m_borderLineDis || m_corners[0].y > Screen.currentResolution.height - m_borderLineDis) { m_bookImageRect.position = m_tempPos; } if (m_corners[1].x > Screen.currentResolution.width - m_borderLineDis || m_corners[1].y < 0 + m_borderLineDis) { m_bookImageRect.position = m_tempPos; } if (m_corners[2].x < 0 + m_borderLineDis || m_corners[2].y < 0 + m_borderLineDis) { m_bookImageRect.position = m_tempPos; } if (m_corners[3].x < 0 + m_borderLineDis || m_corners[3].y > Screen.currentResolution.height - m_borderLineDis) { m_bookImageRect.position = m_tempPos; } } if (Input.GetMouseButton(2)) { m_bookImageRect.position = GameObject.Find("MainUI").transform.position; } }