Vojtěch Bursa
Vojtěch Bursa

Reputation: 23

Unity look at cursor in 2d

I'm creating 2D game in Unity 3D, but I have problem with my player rotation. It should rotate to the cursor, but when I start the game, its looking at Main camera.
I've tried lots of codes from lots of tutorials, but in most of it, my player is only looking to the center of Main camera.
This is my code now:

Vector3 mouse = Input.mousePosition;

    Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3 (mouse.x, mouse.y, player.transform.position.y));

    Vector3 forward = mouseWorld - player.transform.position;
    player.transform.rotation = Quaternion.LookRotation (forward, Vector3.up);


Player is only looking to the camera. I'm not expert, but I think there is some problem with input, because some codes, that I've tried in past, did, that the player was only looking to nothing
(I'm not best in english... please apologize my mistakes)

Upvotes: 1

Views: 5182

Answers (1)

Hieu Nguyen Trung
Hieu Nguyen Trung

Reputation: 104

You can use:

Vector3 mouse = Input.mousePosition;

    Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3 (mouse.x, mouse.y,transform.position.z));

transform.right = mouseWorld -transform.position;

Upvotes: 1

Related Questions