- Home /
Translate Mouse to Worldspace
I got a plane somewhere in the worldspce. I can detect if the plane is hitten by a mouseclick using Rays:
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
GameObject x = hit.transform.gameObject;
if (x == gameObject) {
GameObject s =GameObject.createPrimitive(PrimitiveType.Sphere);
s.transform.position=hit.point;
}
}
}
So when clicked again, I want to create a new Sphere where the mouse is, which this time havent to be on the plane. I know that I somehow need to translate my 2D coords in 3D. Since I now know the z coordinate this S shouldnt be a problem now or? I tried:
Vector3 downpos=Input.mousePosition;
downpos.z=s.z; // s from pervious code block
downpos=Camera.main.ScreenToWorldPoint(downpos);
But it didnt work. Why? And why isnt downpos equal to hit.point in this example?:
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
Vector3 downpos=Input.mousePosition;
downpos.z=hit.point.z;
downpos = Camera.main.ScreenToWorldPoint(downpos);
Debug.LogWarning(downpos+"?="+hit.point);
}
}
How can I make those two equal?
OffTopic: I would have used better tags if I was allowed to create them.
Raycast, mouse, and worldspace are all existing tags (so I added them); I don't know what else you'd need.
Your answer
Follow this Question
Related Questions
Raycast from 2D canvas object to world space 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
OnMouseDown for Right Mouse 2 Answers
Want to move object slowly to where the mouse clicks? 1 Answer