- Home /
Mouse pos + raycast
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
thanks
Harry
Answer by robertbu · Feb 22, 2013 at 06:49 PM
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;
}
}
}
Your answer
Follow this Question
Related Questions
Raycast in camera 1 Answer
Raycast hitting objects to the left of my player 1 Answer
How can I continue to instantiate an object after deleting 0 Answers
[SOLVED] Raycast only hits one side of the box collider 1 Answer
Grid Placement In Game 2 Answers