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 :
Firstly your function is never called because there is typo in its name. It should be
Update
notupdate
.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 withWorldToScreenPoint
and back withScreenToWorldPoint
, 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: