Position at far right of screen

I’m having some trouble figuring out how to position a game object at the far right hand side of the screen. Here is my code:

Vector3 viewPos = _cameraRef.WorldToViewportPoint(_tr.position);

if(viewPos.x < (0f - gutter)){
	Vector3 newPos = _cameraRef.ViewportToWorldPoint(new Vector3(1f, 1f, _cameraRef.nearClipPlane));
	newPos.z = 0f;
	newPos.y = _tr.position.y;
	_tr.position = newPos;
}

The if statement checks if the player falls outside the left side of the screen. When the position updates, the object appears in the middle of the screen as opposed to the far right hand side. Any have any ideas?

1 Answer

1

viewport space is camera space. you want screen space which is in pixels. the edge of the screen would be screen.width . also when you go from screen to world make sure your z is cam.pos.z - obj.pos.z, else the worldspace you get back won’t be correct.