0

So here is my problem in a nutshell: I want to know how spawn an object in the middle of the screen, which means I want find the screen's width and height values in World units.

Camera Position: 0,23,-10

Camera Rotation: 60,0,0

So I have tried this:

Vector3 screenWorldSize = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, -10));

// In the Update function
If(Input.GetKeyDown(Keycode.P))
{
GameObject tempObject = Instantiate(gamePrefab);
tempObject.transform.position = new Vector3(screenWorldSize.x, 1.5f, 10f);
}

But the tempObject position is not correct (Not in the middle), So I tried to Debug.Log(screenWorldSize) and I get this result (-10.3, 28.8, -20.0)

I tried using Camera.main.ViewPortToWorldPoint() with (0,0,-10) and (1,0,-10) and I got almost the same result.

Here is an image of the scene.. Scene Image

Is there something that I don't understand? How to get the screen edges in World points?

Community
  • 1
  • 1
  • Possible duplicate of https://stackoverflow.com/questions/45310558/unity3d-move-ui-object-to-center-of-screen-while-maintaining-its-parenting – Yauheni Sep 22 '19 at 09:47
  • Hi. Its not a duplicate. Please read the question again My question is not about ui at all, and the question you is no way near of solving my problem. –  Sep 22 '19 at 12:21
  • Hi. And this doesn't work for you? tempObject.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 10) – Yauheni Sep 22 '19 at 12:27
  • Hi again, unfortunately no! this is why I need more help. Believe me I have read almost every Question/Post/Blog about this issue and non of them worked. I'm telling you it's not a duplicate. –  Sep 22 '19 at 19:02

1 Answers1

0

Very simple. You don't need the width and height at all, you just need the direction.

// this is a vector matching the camera's direction
Vector3 cameraDirection = Camera.main.transform.rotation * Vector3.forward;
// this is the camera position
Vector3 cameraPosition = Camera.main.transform.position;

If you want to just create the object a certain distance from the camera, you can do this to get its position

Vector3 position = cameraPosition + cameraDirection * distance;

If you want to spawn the object on another object pointed at by the camera, you need this:

RaycastHit hit;
if (Physics.Raycast(cameraPosition, cameraDirection, out hit))
{
    Vector3 position = hit.point;
    [..]
}
Lou Garczynski
  • 624
  • 3
  • 10