title: Unity 2D - Keep Player Object in Boundary of it's Parent Panel
body: <p>In Unity i have a UI Panel which has a player object (an UI Image object).</p>
  <p>I moving player object into planel with user inputs (keyboard or touch)</p>
  <p>I can't keep player object in it's parent panel,</p>
  <p>Please check below image, I want to keep player inside of Red Panel</p>
  <p>Here is my Tried Code</p>
  <pre><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(&quot;PnlBackground&quot;).GetComponent&lt;RectTransform&gt;();
  
      screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(pnlBackgroundTransform.rect.width  , pnlBackgroundTransform.rect.height , MainCamera.transform.position.z));
  
      objectWidth = transform.GetComponent&lt;SpriteRenderer&gt;().bounds.extents.x; //extents = size of width / 2
      objectHeight = transform.GetComponent&lt;SpriteRenderer&gt;().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;
  }
  </code></pre>
  <p><a href="https://i.stack.imgur.com/Dg0Ku.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dg0Ku.png" alt="enter image description here" /></a></p>