- Home /
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.
Answer by AlucardJay · May 01, 2013 at 12:53 AM
Check my answer here : http://answers.unity3d.com/questions/406636/3d-object-attach-to-mouse-1.html
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.Get$$anonymous$$ouseButtonDown(0)) {
Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
GameObject.CreatePrimitive(CurrentPrimitive).transform.Translate(mRay.origin + (mRay.direction * primDistance));
}
if (Input.Get$$anonymous$$ouseButtonDown(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.
Your answer
Follow this Question
Related Questions
Move JoyStick Together With Camera 1 Answer
Strange Camera Behavior on iOS - Runs perfect in Unity 0 Answers
Rotation always changing values! 1 Answer