- Home /
Direct positioning with a perspective camera?
I'm trying to place objects into the game world at the current mouse position using Camera.ScreenToWorldPoint. It works well with an orthographic camera but not at all with a perspective camera. No matter where the mouse is on the screen or what I manually set the X and Y co-ordinates to (using Instantiate), the objects always show up in the same location.
Is there way of getting ScreenToWorldPoint working with a perspective camera, or is there another function or method that will give me the same results?
Answer by Eric5h5 · Jun 28, 2011 at 05:38 PM
Try using camera.nearClipPlane for the Z distance with ScreenToWorldPoint.
Yes, the x and y will always be the same if z is 0. Try using nearClipPlane for z.
Same results. Here's what I'm doing:
var point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Instantiate(Resources.Load("Sphere_Test"), Vector3(point.x, point.y, Camera.main.nearClipPlane), transform.rotation);
You're not using camera.nearClipPlane for the Z distance with ScreenToWorldPoint though. I meant:
var mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
var point = Camera.main.ScreenToWorldPoint(mousePos);
Instantiate(Resources.Load("Sphere_Test"), point, transform.rotation);
Answer by dareksob · Nov 07, 2012 at 10:11 AM
Hej, i had the same problem. You have to use the farClipPlane not the nearClipPlane as the z axis. Than you get the right ray by current camera.
An example to shoot bullets.
void Update () {
if(Input.GetMouseButtonUp(0)) {
this._position = Input.mousePosition;
Debug.Log(this._position);
this._position.z = Camera.main.farClipPlane;
this._position = Camera.main.ScreenToWorldPoint(this._position);
this._position.Normalize();
GameObject bullet = GameObject.Instantiate(this.bullet) as GameObject;
bullet.transform.position = this.transform.position;
bullet.rigidbody.AddForce(this._position * this.power);
}
Debug.DrawRay(this.transform.position, this._position, Color.red);
Debug.DrawRay(this.transform.position, Camera.mainCamera.transform.forward);
}