Screen to World Position: Can't seem to get it right
Hello,
this seems to be a simple problem, but for some reason the functions don't behave as I expect. Maybe someone could help me with it.
I want to translate two points at the edge od the screen to world space, as pictured here:
So I enter the blue and orange dot's position (Vector2 x is 0-pixelWidth, y is 0-pixelHeight) and want to receive the Vector3 world coordinates as indicated by the arrows. I tried playing around a bit by creating debug objects and positioning them using the Camera.main.ScreenToWorld() method. But both min and max objects are positioned exactly where the camera game object is, which doesn't seem to be correct.
Here is the code:
void Update()
{
Camera cam = Camera.main;
Vector3 cameraOrigin = cam.transform.position;
int screenHalfWidth = Mathf.FloorToInt(cam.pixelWidth * 0.5f);
int screenHalfHeight = Mathf.FloorToInt(cam.pixelHeight * 0.5f);
bool boundsChanged = false;
// Debug Bowl
Vector2 screenMin = Vector2.zero;
Vector2 screenMax = new Vector2(cam.pixelWidth, cam.pixelHeight);
Vector3 worldMin = cam.ScreenToWorldPoint(screenMin);
Vector3 worldMax = cam.ScreenToWorldPoint(screenMax);
DebugBowlMin.transform.position = worldMin;
DebugBowlMax.transform.position = worldMax;
//......
With this test code I want to accomplish to position two debug bowls bottom left (min) and top right (max) according to their respective position in world space, similar to what is pictured in the screenshot. How would I be able to do that?
Taking the two points (blue and orange) why don't you just do this
Vector3 greenWorldPosition = Camera.main.ScreenToWorldPoint(blueScreenPosition);
Vector3 redWorldPosition = Camera.main.ScreenToWorldPoint(orangeScreenPosition);
Hi, I tried that, doesn't work.
Green and Red bowls are positioned at 0/0/0
Code:
void Update() {
Camera cam = Camera.main;
Vector3 cameraOrigin = cam.transform.position;
int screenHalfWidth = $$anonymous$$athf.FloorToInt(cam.pixelWidth * 0.5f);
int screenHalfHeight = $$anonymous$$athf.FloorToInt(cam.pixelHeight * 0.5f);
bool boundsChanged = false;
// Debug Bowl
Vector2 blueDot = new Vector2(0, cam.pixelHeight);
Vector2 orangeDot = new Vector2(cam.pixelWidth, screenHalfHeight);
Vector3 greenBowl = cam.ScreenToWorldPoint(blueDot);
Vector3 redBowl = cam.ScreenToWorldPoint(orangeDot);
DebugBowl$$anonymous$$in.transform.position = greenBowl;
DebugBowl$$anonymous$$ax.transform.position = redBowl;