I have this code bellow for my gameobject :
private float screenx;
Vector3 playerPosScreen;
void Start () {
screenx=Camera.main.pixelWidth-renderer.bounds.size.x ;
}
void update(){
playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
if (playerPosScreen.x >= screenx) {
//playerPosScreen.x=screenx;
transform.position=new Vector3 (screenx, transform.position.y,transform.position.z);
}
//txt.text = playerPosScreen.x.ToString();
else if(playerPosScreen.x<=renderer.bounds.size.x){
transform.position=new Vector3 (renderer.bounds.size.x, transform.position.y,transform.position.z);
}
}
I'm developing a 2D
game with an orthographic
camera,my problem is the gameobject is keep on going out of screen , am i missing something here ?
After some research i found a solution wish worked excellent with me :
Vector3 playerPosScreen;
Vector3 wrld;
float half_szX;
float half_szY;
void Start () {
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 ;
}
void Update () {
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;
}
}
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:
Vector2 playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
if (playerPosScreen.x > Screen.width)
{
transform.position =
Camera.main.ScreenToWorldPoint(
new Vector3(Screen.width,
playerPosScreen.y,
transform.position.z - Camera.main.transform.position.z));
}
else if (playerPosScreen.x < 0.0f)
{
transform.position =
Camera.main.ScreenToWorldPoint(
new Vector3(0.0f,
playerPosScreen.y,
transform.position.z - Camera.main.transform.position.z));
}