Clamp player to screen borders

Hi guys,

Im working on 2.5D top down shooter for iOS and Android and I need to clamp player position to avoid the player leave game screen.
My game setup is camera, moving along Z axis at 60 degrees angle and the player is moving along x,z axis.

Is there any way how to overcome this?

Alright, I’ve figured it out, apparently I made a stupid mistake.

This is the new script, I tested it and it works as it should be. Make sure the camera that is rendering the player is the main camera. Else you have to change the script a little bit.

function Update () 
{


    
        var dist =(transform.position.y - Camera.main.transform.position.y);
		
        var leftLimitation = Camera.main.ViewportToWorldPoint(Vector3(0,0,dist)).x;
        var rightLimitation = Camera.main.ViewportToWorldPoint(Vector3(1,0,dist)).x;
	
        var upLimitation = Camera.main.ViewportToWorldPoint(Vector3(0,0,dist)).z;
        var downLimitation = Camera.main.ViewportToWorldPoint(Vector3(0,1,dist)).z;
    

	
	
    transform.position.x = Mathf.Clamp(transform.position.x,rightLimitation,leftLimitation);
    transform.position.z = Mathf.Clamp(transform.position.z,downLimitation,upLimitation);
}

Image so you can understand the principe:

125alt text125

The principle remains the same:

-First we create a variable dist, this variable calculates the distance between the players y position and the y position of the camera.

  • Then we create four variables, leftLimitation and so on. Camera.main.ViewportToWorldPoint calculates the cameras borders and converts them to world coordinates so we can restrict the players transform. We do this both for the x and z axis because these are the axis the player moves along.
  • List item
  • Then we create a function that restricts the players position both for the x and z axis.

I hope this solves your problem, sorry for my previous wrong answer.