The object still leaves the boundries

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

public class player : MonoBehaviour
{

    [SerializeField] float moveSpeed = 10f;
    

    float Xmin;
    float Xmax;
    float Ymin;
    float Ymax;

    // Use this for initialization
    void Start()
    {
        managemovement();

    }

    private void managemovement()
    {
        Camera gamecamera = Camera.main;
        Xmin = gamecamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;

        Xmax = gamecamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
        Ymin = gamecamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y;
        Ymax = gamecamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y;




    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    private void Move()
    {

        var deltaX =  Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
        var newXPos = transform.position.x + deltaX;
        var deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
        var newYPos = transform.position.y + deltaY;
        transform.position = new Vector2(newXPos, newYPos);
        newXPos = Mathf.Clamp(transform.position.x + deltaX, Xmin, Xmax);
        newYPos = Mathf.Clamp(transform.position.y + deltaY, Ymin, Ymax);
    }

}


Hi Usman,

Which object do you mean?

Since the pivot point is usually located in the centre of a sprite, you will have to take the width of your sprite into consideration when calculating the clamp values.

Try this changes

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

public class player : MonoBehaviour
{

    [SerializeField] float moveSpeed = 10f;
    

    float Xmin;
    float Xmax;
    float Ymin;
    float Ymax;

    // Use this for initialization
    void Start()
    {
        managemovement();

    }

    private void managemovement()
    {
        Camera gamecamera = Camera.main;
        Xmin = gamecamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;

        Xmax = gamecamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
        Ymin = gamecamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y;
        Ymax = gamecamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y;




    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    private void Move()
    {

        var deltaX =  Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
        var deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
        var newXPos = transform.position.x + deltaX;
        var newYPos = transform.position.y + deltaY;        
        newXPos = Mathf.Clamp(newXPos, Xmin, Xmax);
        newYPos = Mathf.Clamp(newYPos, Ymin, Ymax);
        transform.position = new Vector2(newXPos, newYPos);
    }

}