Question by
Aprentis · Feb 14, 2021 at 02:27 AM ·
rotationdirectionscreentoworldpoint
How do I make my character face towards the mouse cursor?
I am using the function ScreenToWorldPoint. The problem is that the closer the mouse cursor is to the player, the less the player is going to face the mouse cursor. Here is the code I am using to rotate the player.
public class LookTarget : MonoBehaviour
{
[SerializeField, Range(0,10)]
private float rotationSpeed = 1f;
void Update()
{
Vector3 mousePosition =new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(mousePosition);
Debug.Log(mouseWorldPos);
LookAtTarget(mouseWorldPos);
}
//Rotates the player given a position in the world
void LookAtTarget(Vector3 target)
{
//Gets the direction in which the player has to face just in the x and z axis
//(I take just x and z because I don't want the player to rotate up and down)
Vector3 direction = Vector3.Scale((target - transform.position), new Vector3(1, 0, 1));
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
}
}
Comment
Your answer
Follow this Question
Related Questions
Object rotates normaly while moving, then does zig zags? 0 Answers
Using Quaternion orientation with a direction vector 1 Answer
How to get the direction based on rotation 0 Answers
Locking facing direction or changing it after following the mouse position 0 Answers
Multiplayer game - Make other players sprites face correct direction. (Logic question) 0 Answers