Answer the question
In order to leave comments, you need to log in
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:
And as the player sees:
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:
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);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question