Create a cube relative to camera & mouse position.

So lets say i have a completely empty scene.

When the user clicks on the screen, i want a cube to appear, 20 units away from the camera and to spawn based on the mouse position - e.g. its centered on the mouse when the mouse is clicked.

How do i go about coding this? I thought about using RayCast, but since the scene is completely empty, there is nothing for the Ray to hit.

Thanks in advance!

-Tristen.

1 Answer

1

Check my answer here : Attach 3D object to mouse - Questions & Answers - Unity Discussions

Cast a ray from the camera to the world :

var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);

Find that point in world 3D space :

var point : Vector3 = ray.origin + (ray.direction * distance);

Wow, that was fast! Thanks for the answer. I'll test it out right now.

Hmm. For some reason it isn't working. Here is my code (in the update() function) if (Input.GetMouseButtonDown(0)) { Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition); GameObject.CreatePrimitive(CurrentPrimitive).transform.Translate(mRay.origin + (mRay.direction * primDistance)); }

if (Input.GetMouseButtonDown(0)) { Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition); GameObject object = GameObject.CreatePrimitive(CurrentPrimitive); object.transform.position = mRay.origin + (mRay.direction * primDistance) }

I forgot to say thank you, and set your answer as correct. So: Thanks! It works.