Y
Y
Yuri Kai2020-01-31 19:14:57
Unity
Yuri Kai, 2020-01-31 19:14:57

How to rotate the weapon towards the cursor?

I need to rotate an object (hand) in the direction of the cursor.

Let me explain, I have a project in 3D space, the player moves only along the Z and Y axes, here is an example:
5e344ebcadf01516420030.png
And as the player sees:
5e344ed16d62f086493537.png

Now to the problem itself, I already know the position of the cursor (in the figure, the position of the cursor is shown in red square) but by the formula (rotationX = Mathf.Atan2(difference.y, difference.z) * Mathf.Rad2Deg) the rotation of the hand is not correctly calculated and it looks something like this:
5e345080a8727327544053.png

And also the code:

using UnityEngine;

public class HandController : MonoBehaviour
{
    public Vector3 cursor; // Положение курсора
    public Vector3 difference;
    public float rotationX; // Вращение объекта
    [SerializeField] GameObject game; // Объект курсора

    void Update()
    {
        cursor = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.y));
        game.transform.position = cursor;
        difference = cursor - transform.position;


        rotationX = Mathf.Atan2(difference.y, difference.z) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(rotationX, 0f, 0f);
    }
}


Tell me how to find the rotation of the "hand" in my case, it also doesn't work through LookAt, here's an example: the
formula is transform.LookAt(new Vector3(transform.position.x, cursor.y, cursor.z));
5e345278a0248803416651.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question