Keep Cursor In Bounds of Camera

Im Currently Working On A Game And Using A Fake Mouse To Control EveryThing. At The Moment, I Have A Bound System So The Cursor Stays WIthin The Ortho Camera Bounds, But The Problem Is That It Only Works On The Right Side And Not The Left Here Is The Script :

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

public class StayWithinBounds : MonoBehaviour
{
public Camera MainCamera;
private Vector2 screenBounds;
private float objectWidth;
private float objectHeight;

// Use this for initialization
void Start()
{
}

// Update is called once per frame
void LateUpdate()
{
    screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.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
    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);
    transform.position = viewPos;
}

}

This: screenBounds.x * -1 + objectWidth should be 0 + objectWidth. The left edge of the screen is 0, not the negative screen width. The same is true for the bottom edge of the screen with is also 0. The width and height of the screen denotes the whole width and height, not just half. Screen space has the origin in the bottom left corner. Clipspace coordinates have the origin in the screen center, but you rarely have to deal with them.

I just realized that you don’t really use screen space coordinates but you converted them to worldspace. That of course means that the bottom left corner of your screen is usually not at (0,0). So you have to use

var origin = MainCamera.ScreenToWorldPoint(new Vector3(0,0,0));

to get the world space position of the bottom left corner.

Note that using worldsapce coordinates for this is generally not a good approach. It will break down as soon as your camera is rotated in any way. It’s usually much simpler to do the opposite. Convert the position you want to clamp into screenspace, clamp it between 0 and Screen.width / height and once clamped convert it back to worldspace.

Here is a quick diagram sorry for the writing lol :

and here is what happens with ur help :