P
P
Pavel Khodalitskiy2021-04-05 11:22:11
Unity
Pavel Khodalitskiy, 2021-04-05 11:22:11

How to stop UI panel from moving when it reaches screen border in Unity?

There is a panel that moves when you click on a certain area of ​​the screen.

606ac790025aa619631494.png
We need to make it so that the panel stops moving after reaching the edge of the camera / screen.

Source:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UpgradeMenuScript : MonoBehaviour
{
    public RectTransform upgradeMenu;

    private Rect leftPart = new Rect(0, 0, Screen.width / 3, Screen.height);
    private Rect rightPart = new Rect(Screen.width / 3 * 2, 0, Screen.width / 3, Screen.height);
    private Rect upperPart = new Rect(0, Screen.height / 3 * 2, Screen.width, Screen.height / 3);
    private Rect downPart = new Rect(0, 0, Screen.width, Screen.height / 3);

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (leftPart.Contains(Input.mousePosition))
            {
                upgradeMenu.transform.Translate(new Vector2(15, 0) * Time.deltaTime);
            }
            if (rightPart.Contains(Input.mousePosition))
            {
                upgradeMenu.transform.Translate(new Vector2(-15, 0) * Time.deltaTime);
            }
            if (upperPart.Contains(Input.mousePosition))
            {
                upgradeMenu.transform.Translate(new Vector2(0, -15) * Time.deltaTime);
            }
            if (downPart.Contains(Input.mousePosition))
            {
                upgradeMenu.transform.Translate(new Vector2(0, 15) * Time.deltaTime);
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
namee, 2021-04-05
@Pleiada

And what's stopping you? Set up a check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question