Clamp a player to the edge of screen when the resolution changes


I am new to using Unity (although my confidence is growing) and I am new to C#. For this project I am working on we are making a side scrolling shooter. Last night i managed to set up my GUI pause menu so it positions itself correctly when the screen resolution changes.

I want to achieve the same thing with my clamping. At the moment I have clamped the player on screen using Mathf.Clamp using this code…

private int minXValue = -8;

private int maxXValue = 8;

private int minYValue = -3;

private int maxYValue = 5;

	Vector3 pos = transform.position;
	pos.y = Mathf.Clamp (pos.y, minYValue, maxYValue);
	pos.x = Mathf.Clamp (pos.x, minXValue, maxXValue);
	transform.position = pos;

However when the resolution changes naturally the positions I have stated no longer apply (well the Y value works fine). I would like some help to clamp the player to the edge of the screen when the screen resolution changes. Thanks for reading :slight_smile:

EDIT - Forgot to mention that the clamping code is inside update.

Your min/max values should be floats, not ints.

A way to find the corners of the screen is to use Camera.ViewportToWorldPoint(); In order to make this work, you need to know the distance from the camera to the players. Then you can do something like:

void Start() {
   Vector3 lowerLeftCorner = Camera.main.ViewportToWorldPoint(, dist);
   Vector3 upperRightCorner = Camera.main.ViewportToWorldPoint(new Vector3(1.0, 1,0,dist));
    minXValue = lowerLefCorner.x;
    maxXValue = upperRightCorner.x;

Another solution is to use the ratio of screen width to height. Something like:

void Start() {
  float halfHeight = (maxYValue - minYValue) / 2.0;
  maxXValue = halfHeight * Screen.width/Screen.height;
  minxXalue = -maxXValue;

Note this second solution assumes the camera is centered left/right on the X axis (as indicated by your -8/8).