- Home /
Set screen boundaries with code
Hello, i'm making a 2d space shooter game and I want to set the screen boundaries for the player using code, which will have the player stop at the edge of the screen for different aspect ratios. How would this be accomplished?
by the way, im trying to avoid using extra gameobjects to use for the boundaries, so please dont include that as part of the solution :)
Um yes, here's my code:
function Update()
{
//// $$anonymous$$ovement ////
//set screen Bounds
screenBounds = Vector3(Screen.width, 0, Screen.height);
//set offset
screen.x = (screenBounds.x*4)/100; //4% of screenBounds.x
screen.y = Screen.height;
//$$anonymous$$ove the player.
directionH = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
playerPos = transform.position;
playerPos.x = playerPos.x + directionH;
transform.position = playerPos;
//set players position in screen coordinates
playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
//transform.position = Camera.main.ScreenToWorldPoint(Vector3(playerPosScreen.x,screen.y,playerPosScreen.z));
if(playerPosScreen.x > screenBounds.x-screen.x)
{
transform.position = Camera.main.ScreenToWorldPoint(Vector3(screenBounds.x-screen.x,playerPosScreen.y,playerPosScreen.z));
}
else if(playerPosScreen.x < screenBounds.x/2-screen.x)//not where I want the player at the moment, ignore this
{
transform.position = Camera.main.ScreenToWorldPoint(Vector3(screenBounds.x/2-screen.x,playerPosScreen.y,playerPosScreen.z));
}
}
So Basically, the code here works like I want it to if right wing of the player ship hits the screen boundaries, and cannot go further. This works fine and dandy on some aspect ratio settings, but when I switch to something like 16:9, half the ship is outside the screen..
Answer by L0932 · Aug 18, 2013 at 06:56 AM
Oh, nevermind..The code works fine. The background image caused some confusion.
how did u set boundaries with different devices ratio or screen sizes?