imtouchk
imtouchk

Reputation: 41

Make character look at mouse in Unity

So I have this code which should make the character look at the mouse. The character doesn't actually look at the mouse, and I don't know what's the causse.

float CameraDistance = Camera.main.transform.position.y - transform.position.y;
Vector3 WorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
WorldPoint.z = CameraDistance;

float AngleRad = Mathf.Atan2(WorldPoint.y - transform.position.y, WorldPoint.x - transform.position.x);
float AngleDeg = (180 / Mathf.PI) * AngleRad;

Body.rotation = AngleDeg;

The red dot is where my mouse actually is.

Upvotes: 0

Views: 7250

Answers (2)

imtouchk
imtouchk

Reputation: 41

I finally managed to fix it. Here's the code:

Vector3 WorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);

Vector3 Difference = WorldPoint - transform.position;
Difference.Normalize();

float RotationZ = Mathf.Atan2(Difference.y, Difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, RotationZ - 90);

I had to substract 90 from RotationZ so that the rotation would be accurate to the mouse position.

Upvotes: 0

MarekK
MarekK

Reputation: 438

Instead of doing math operations, you should really look into transform.LookAt(). This method will solve this problem

Also instead of Camera.main, you should use Input.mousePosition

var mousePos = Input.mousePosition;
var wantedPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, depth));

Body.LookAt(wantedPos);

Upvotes: 2

Related Questions