What im trying to do is to instantiate an object where the mouse is in a 2d game. I use a raycast but want the raycast to follow the mouses x and y coordinates from the camera view. ive tryed all things under the sun and after countless hours looking on the forums and answers i cant find a fix. c# preferably
One solutions is to use Camera.ScreenToWorldPoint(). Note that the Z value you set is the distance in front of the camera. So you will set that to the distance between your camera and you 2D game surface. Here is a sample script. Attach to an empty game object and click the mouse:
public class CreateAtMouse : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown(0))
{
Vector3 v3Pos = Input.mousePosition;
v3Pos.z = 10.0f;
v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.position = v3Pos;
}
}
}