NGUI位置计算
判断是否在屏幕内
private void Awake()
{
screenHeight = (float)Screen.height;
screenWidth = (float)Screen.width;
if ((float)Screen.width / Screen.height > (float)UIRoot.list[0].manualWidth / UIRoot.list[0].manualHeight)
{
screenScale = UIRoot.list[0].manualHeight / screenHeight;
manualHeight_2 = UIRoot.list[0].manualHeight / 2;
manualWidth_2 = (int)(Screen.width * screenScale) / 2;
}
else
{
screenScale = UIRoot.list[0].manualWidth / screenWidth;
manualHeight_2 = (int)(Screen.height * screenScale) / 2;
manualWidth_2 = UIRoot.list[0].manualWidth / 2;
}
}
private bool IsInScreen(Vector3 pos)
{
if (pos.x < -1 * manualWidth_2 || pos.x > manualWidth_2 || pos.y < -1 * manualHeight_2 || pos.y > manualHeight_2)
{
return false;
}
else
{
return true;
}
}
这种计算是针对NGUI适配模式为Constrained。如果屏幕宽高比大于开发时的宽高比,说明屏幕更宽。这时候以高度为适配。否则以宽度适配。得出实际的宽高。
参考:
Unity NGUI屏幕适配
判断是否点击了屏幕
private bool _checkMouseClick = false;
public void Update()
{
if (_checkMouseClick && (Input.GetMouseButton(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved))) {
if (TextPanel.activeSelf) {
TextPanel.CustomSetActive(false);
_checkMouseClick = false;
}
}
}计算点击位置
void SetAnchor(Vector2 screenPos)
{
// Vector2 screenPos = UICamera.lastEventPosition;
Vector3 worldPos = UICamera.currentCamera.ScreenToWorldPoint(new Vector3(Mathf.Clamp(screenPos.x, BG.width * ((float)Screen.width / (float)UIRoot.list[0].manualWidth) / 2, (Screen.width - BG.width * ((float)Screen.width / (float)UIRoot.list[0].manualWidth) / 2)), screenPos.y));
Bounds abs = NGUIMath.CalculateAbsoluteWidgetBounds(controller.transform.GetChild(0));
float aspect = (float)Screen.width / (float)Screen.height;
Vector4 worldMargin = Margin * 2.0f / (float)UIRoot.list[0].manualHeight;
worldPos.x = Mathf.Clamp(worldPos.x, -aspect + worldMargin.x, aspect - worldMargin.y);
Vector3 currentPos = controller.transform.GetChild(0).position;
currentPos.x = worldPos.x;
if (worldPos.y >= 1f - worldMargin.w - abs.size.y - 0.2f)
{
currentPos.y = worldPos.y - abs.size.y / 2 - 0.1f;
}
else
{
currentPos.y = worldPos.y + abs.size.y / 2 + 0.1f;
}
controller.transform.GetChild(0).position = currentPos;
}

浙公网安备 33010602011771号