Skip to content Skip to sidebar Skip to footer

Trying To Keep A Game Object Within The Screen Left And Right Bounds In Unity3d

I have this code bellow for my gameobject : private float screenx; Vector3 playerPosScreen; void Start () { screenx=Camera.main.pixelWidth-renderer.bounds.size.x ; } void upda

Solution 1:

After some research i found a solution wish worked excellent with me :

Vector3 playerPosScreen;
Vector3 wrld;
float half_szX;
float half_szY;
voidStart () {
    wrld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f));
    half_szX = renderer.bounds.size.x / 2;
    half_szY = renderer.bounds.size.y /2 ;
}
voidUpdate () {
    playerPosScreen = transform.position;
 if (playerPosScreen.x >=(wrld.x-half_szX) ) {
        playerPosScreen.x=wrld.x-half_szX;
        transform.position=playerPosScreen;
    }
    if(playerPosScreen.x<=-(wrld.x-half_szX)){
        playerPosScreen.x=-(wrld.x-half_szX);
        transform.position=playerPosScreen;
    }
}

Solution 2:

Firstly your function is never called because there is typo in its name. It should be Update not update.

Secondly the problem with coordinates is that the code is mixing screen coordinates and world coordinates. Screen coordinates go from (0, 0) to (Screen.width, Screen.height). Coordinates can be changed from world coordinates to screen coordinates with WorldToScreenPoint and back with ScreenToWorldPoint, in which the Z value is the distance of the converted point from camera.

Here is a complete code example, which can be used after changing the player's position to make sure that it is inside the screen area:

Vector2playerPosScreen= Camera.main.WorldToScreenPoint(transform.position);
    if (playerPosScreen.x > Screen.width)
    {
        transform.position = 
            Camera.main.ScreenToWorldPoint(
                newVector3(Screen.width, 
                            playerPosScreen.y, 
                            transform.position.z - Camera.main.transform.position.z));
    }
    elseif (playerPosScreen.x < 0.0f)
    {
        transform.position = 
            Camera.main.ScreenToWorldPoint(
                newVector3(0.0f, 
                            playerPosScreen.y, 
                            transform.position.z - Camera.main.transform.position.z));
    }

Post a Comment for "Trying To Keep A Game Object Within The Screen Left And Right Bounds In Unity3d"