Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

902
Views
Unity 2D - Keep Player Object in Boundary of it's Parent Panel

In Unity i have a UI Panel which has a player object (an UI Image object).

I moving player object into planel with user inputs (keyboard or touch)

I can't keep player object in it's parent panel,

Please check below image, I want to keep player inside of Red Panel

Here is my Tried Code

public Camera MainCamera; //be sure to assign this in the inspector to your main camera
private Vector2 screenBounds;
private float objectWidth;
private float objectHeight;
private RectTransform pnlBackgroundTransform;


private void Start()
{
    pnlBackgroundTransform = GameObject.Find("PnlBackground").GetComponent<RectTransform>();

    screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(pnlBackgroundTransform.rect.width  , pnlBackgroundTransform.rect.height , MainCamera.transform.position.z));

    objectWidth = transform.GetComponent<SpriteRenderer>().bounds.extents.x; //extents = size of width / 2
    objectHeight = transform.GetComponent<SpriteRenderer>().bounds.extents.y; //extents = size of height / 2
}

void LateUpdate()
{
    Vector3 viewPos = transform.position;
    viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x * -1 + objectWidth, screenBounds.x - objectWidth);
    viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y * -1 + objectHeight, screenBounds.y - objectHeight);
    Debug.Log(screenBounds);
    Debug.Log(viewPos);
    transform.position = viewPos;
}

enter image description here

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I'd say it's not very usual having the player implemented as a UI element, and instead you should be implementing it outside the UI/Canvas system.

The UI/Canvas system uses a set of rules of placing and scaling to deal with responsive design. You have at least 4 values (excluding rotation) to place something on the screen: anchor, pivot, position and scale.

For example: if you want to create a square you can either set it's size in absolute pixel values or relative values (to parent). If you're using absolute values, your UI Scale Mode, defined on the Canvas object, should affect the visual results.

UI absolute vs relative

This means the UI/Canvas is for elements that should adapt to the screen, such as buttons, dialogs, labels, etc. Taking advantage of device parameters to improve the UX.

Outside the UI/Canvas system, things are directly based on Linear Algebra: you have a 3D vector space (a "World") where everything exists with an absolute size and position. Then, your Camera stretches and twists the whole world to match what your current perspective. That means your object will always have the same size, regardless of screen size.

Camera size

Now, assuming you have a very specific reason to implement your game into UI, there are a few ways you can do it. I'll assume you're using absolute values. Please note all the units used here are pixels, and the effect should be different for devices with different resolutions and sensible to the UI Scale Mode parameter. Also, please note I've set both anchors min and max to (0,0), the bottom left corner (default is screen center, (0.5,0.5)), in order to avoid negative coordinates.

The following script is attached to the player's UI Image.

public class UIMovementController : MonoBehaviour
{
    public float speed = 5.0f;

    new private RectTransform transform;
    private Rect canvasRect;
    
    private void Start()
    {
        transform = GetComponent<RectTransform>();
        canvasRect = GetComponentInParent<Canvas>().pixelRect;
    }

    void Update()
    {
        // Keyboard Input (Arrows)

        Vector2 move = new Vector2(0,0);
        if (Input.GetKey(KeyCode.UpArrow)) { move.y += speed; }
        if (Input.GetKey(KeyCode.DownArrow)) { move.y -= speed; }
        if (Input.GetKey(KeyCode.LeftArrow)) { move.x -= speed; }
        if (Input.GetKey(KeyCode.RightArrow)) { move.x += speed; }
        transform.anchoredPosition += move;

        // Position clamping
        
        Vector2 clamped = transform.anchoredPosition;
        clamped.x = Mathf.Clamp(clamped.x, transform.rect.width / 2, canvasRect.width - transform.rect.width / 2);
        clamped.y = Mathf.Clamp(clamped.y, transform.rect.height / 2, canvasRect.height - transform.rect.height / 2);
        transform.anchoredPosition = clamped;
    }
}

UI Movement Clamping

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!