0
\$\begingroup\$

I have a plane GameObject on which I want to place cubes. The user can move the cube around on the plane and when LMB is clicked, the cube is placed at that position. Everything works great, besides the position of the cube is not that accurate. In the center of my plane, mouse pointer and cube position match perfectly, moving the mouse along the x-Axis also works fine, but up or down (z-axis in game world) doesn't work well, the mouse moves "more" than the cube object. Here's photos of the issue:

cube position problem

and here's my source code:

void Update()
    {
        Vector3 m = Input.mousePosition;
        Vector3 n = Camera.main.ScreenToWorldPoint(new Vector3(m.x, m.y, 1));
        float camDistance = (float)Math.Sqrt((Math.Pow(n.y, 2.0f) + Math.Pow(6, 2.0f)));
        Vector3 p = Camera.main.ScreenToWorldPoint(new Vector3(m.x, m.y, camDistance));

        cube.position = new Vector3(p.x, 0.3f, p.z);
    }

At first I used camDistance as a constant that doesn't change (distance from the camera to the center of the plane), then I tried to adjust it depending on where the object is (distance from the camera to the mouse position in world coordinates). It still doesn't look great, so I need some help.

Thank you!

\$\endgroup\$
1
\$\begingroup\$

I suggest using a raycast for this, either a physics one or a collider one. It's way easier than dishing out your own math calculations (probably faster and less of a resource hog too).

Something like this

Vector3 hitPosition;
void Update()
{
    if(Input.GetMouseButtonDown(0)) //check if the LMB is clicked
    {
        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit)) //check if the ray hit something
        {
            hitPosition = hit.point; //use this position for what you want to do
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ I also suggest digging deeper into the Unity framework instead of trying to find your own way through C#. They're professionals too, try to use their tools first, then invent your own as necessary. \$\endgroup\$ – John Hamilton Dec 11 '16 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.