Instantiate at mouseposition problem

Hello all,

I’m trying to instantiate an object at my mouseposition when I type ‘i’.

Here’s my code:

if(Input.GetKeyDown("i"))
		{
			print("input: " + Input.mousePosition);
			Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
			//pos.y = 0;
			print("pos: " + pos);
			Debug.Break();
			cObject = (GameObject) GameObject.Instantiate(prefab, pos, Quaternion.identity);
		}

However, when I type ‘i’ in the gameview, it instantiates the object at the Cameraposition, not at the mouseposition. I’ve used Camera.ScreenToWorldPoint and Instantiate before, but not together. Is there something I’m missing?

Well you told it to do so.

Basically your problem is your trying to use 2d coordinates and get a 3d point.

Screen to world point from mouse will work but the mouse is basically at the cameras position.

What you need to do it give the object a predefined depth, that is what your missing, your spawning it in the cameras plane just slightly moved from it.

do something like

depth = 3;

pos = new vector3(input.mouse.x, input.mouse.y, depth);

Start with 3 for the depth, thats a good easy to see it now distance. Then change the depth to suit your needs, you can even assign the mouse scroll wheel to modify the depth value. Best of luck! Mark as answered if so.

Your issue is simple, you need to cast a ray using raycast from your pos

var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
    Debug.DrawLine (ray.origin, hit.point);
}
GameObject obj = (GameObject)Instantiate(prefab,hit.point,Quaternion.identity);

Problem was you were converting from the screen to the real world of the game but still on the camera screen. You need to throw a laser beam from that point to the world and where it hits is what you are pointing with the mouse.

@FlyingOstriche is right: a single point in the 2D screen corresponds in the 3D world to an infinite line passing through the camera and the mouse pointer, thus you must specify which point of this line you want. ScreenToWorldPoint selects this point based on the Z coordinate: it must be the distance from the camera - if you pass Input.mousePosition, z is zero and the point returned is exactly the camera position.

You can pass a constant in Z like this:

  ...
  Vector3 mPos = Input.mousePosition;
  mPos.z = 20.0f; // select point at 20 units
  Vector3 pos = Camera.main.ScreenToWorldPoint(mPos);
  ...