I
I
ikeky2020-07-24 15:24:01
C++ / C#
ikeky, 2020-07-24 15:24:01

Why can't the player turn to the cursor in a 3d top-down game?

I'm making a 3d game, and as for me, this 3dness is the main problem of the inaccuracy of the player's rotation in the direction of the cursor.
Here is the player code:

void Update(){
   RaycastHit hit;
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   if (Physics.Raycast(ray, out hit)){
      Vector3 pointToLook = hit.point;
      transform.LookAt(2 * transform.position - pointToLook);
   }
}

If I use Camera.main.ScreenPointToRay and transform.LookAt, maybe they are not optimal for this task.
error video

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ikeky, 2020-07-24
@ikeky

They found a solution for me in a foreign stackoverflow site, where they perfectly described the error, you can find more about this problem here
Here is the solution:

Debug.Log(Input.mousePosition);
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit)){
            Vector3 pointToLook = hit.point;
            Vector3 projection = Vector3.ProjectOnPlane(transform.position - pointToLook, Vector3.up);
            transform.forward = projection;
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question