Search Unity

Make player stay in Screen

Discussion in '2D' started by SmashteamGX, Jul 21, 2016.

  1. SmashteamGX

    SmashteamGX

    Joined:
    Jul 21, 2016
    Posts:
    3
    I am trying to make a script to make player not be able to get out of screen but i get error mesage mising semi collen
    i have tryed to fix it for about 3 hours and i simply anybody knows how i can fix this? Thanks.


    #pragma strict

    public var speed : int = 10;
    var shipBoundaryRadius = 0.5;

    function Start () {

    }

    function Update ()
    {

    if(Input.GetAxis("Horizontal"))
    {
    transform.Translate(Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, 0));
    }
    if(Input.GetAxis("Vertical"))
    {
    transform.Translate(Vector3(0, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0));
    }

    Vector3 pos = transform.position;

    if(pos.y+shipBoundaryRadius > Camera.main.orthographicSize)
    {
    pos.y = Camera.main.orthographicSize - shipBoundaryRadius;
    }
    if(pos.y-shipBoundaryRadius < -Camera.main.orthographicSize)
    {
    pos.y = -Camera.main.orthographicSize + shipBoundaryRadius;
    }

    // Now calculate the orthographic width based on the screen ratio
    float screenRatio = (float)Screen.width / (float)Screen.height;
    float widthOrtho = Camera.main.orthographicSize * screenRatio;

    // Now do horizontal bounds
    if(pos.x+shipBoundaryRadius > widthOrtho)
    {
    pos.x = widthOrtho - shipBoundaryRadius;
    }
    if(pos.x-shipBoundaryRadius < -widthOrtho)
    {
    pos.x = -widthOrtho + shipBoundaryRadius;
    }

    // Finally, update our position!!
    transform.position = pos;

    }
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,411
  3. mholmes

    mholmes

    Joined:
    Dec 8, 2012
    Posts:
    414
    Just a tip when doing 2d games. Most of the time the player has very little movement and typically centered in the screen. example

    Screen Player Screen
    { { } }

    So you let your player have a little movement but ultimately your creating an optical illusion. the background is what moves not the player. An when they "move" your moving blocks of objects forward and backward in sync with the background. Think of it as a giant grid. You draw your screen objects when the grid object is not visible and move in when its rendered so it will not glitch. To the statement above yes you have to switch to Mono for Visual Studio to get the latest. I write my games in .Net but Mono is good stuff too. Anyway, I hope that helps explain char position. Play a old video game some time and watch your char move on the screen. Super Mario is a game that comes to my mind you can clearly see the illusion.