C
C
ChelSiharpniy2022-03-19 17:46:09
C++ / C#
ChelSiharpniy, 2022-03-19 17:46:09

How to fix a bug with MousePosition?

public void OnMouseDrag()
    {
        transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }


Here is the code to move the object with the cursor, but the object automatically moves to the camera, that is, along the Z coordinate, and becomes invisible

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mgvark, 2022-03-20
@ChelSiharpniy

the problem is that your mouse on the screen is 2D and the world is 3D.
your mouse can move up and down, left and right on the screen, but it can never "enter" or "leave" the screen, its depth is zero.
Thus, when converting from mouse to 3D, you must determine the depth yourself.
in this case you would normally just copy the existing z-axis to be
transform.position = new vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y, transform.position .z);
it's not ideal, you should create one instance of vector3 and keep reassigning it instead of creating new variables every time maybe and maybe the Camera.main.ScreenToWorldPoint(Input.mousePosition) variable just for readability.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question