[2D] Lookat doesn't use Z coord to look at my object..

EDIT: Solution in below comment (CTRL+F “solution:”)

Hello all,

I have a character who has a hand I want to look at the mouse at all times. When I start the game, if I don’t move, the hand will always orient to point at my cursor. However, once I move around and jump a few times, lookat()'s z coord no longer aligns with my cursor.

Here’s my code:

	void Update ()
    {
        Vector3 mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
        mousePos.z = 0;
        this.transform.LookAt(mousePos);


//below unnecessary to orientation, but included as to include entire update function


        debugText.text = "test " + mousePos.ToString();

        //if(nothing equipped)
        //hand.active = true; //sets visible or not

        if(Vector2.Distance(mousePos, player.transform.position) > 2)
        {
            hand.position = player.transform.position + (mousePos - player.transform.position).normalized * 2;
        }
        else
        {
            hand.position = mousePos;
        }
	}

Before:

After:

Any ideas on why it stops orienting?

Shameless bump.

I’m not at home or I would try orienting the hand via LookAt() after I move the hand instead of the current layout. Other than that I’m not sure what to try.

Instead of :-

Vector3 mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
 mousePos.z = 0;
 this.transform.LookAt(mousePos);

You could try

Vector3 mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(mousePos,Vector3.forward);
transform.eulerAngles=new Vector3(0,0,-transform.eulerAngles.z);

This works for me, just tested it.

This does not work for me, unfortunately. The hand is meant to rotate with the player, whereas this blocks the rotation of the x and y axis, and appears to negate the z axis as well. After manually setting the z-coord to 0, the hand will at least line up on the z axis as it did. The rotation is still a problem for me.

Here’s a pic of what happens. For reference, my mouse is pointed at the top of the left lightpost as seen in earlier pictures:

1504917--84980--$example.png

And when Z vector is set to 0 every update:

Thank you for the response.

Solution:

Silly me was using LookAt() to only reference the mouse position instead of the mouse position relative to where the player is. I have a separate GO for my hand since it will be using various models for guns and such. When I called LookAt(), it assumed my hand was still in it’s original (0,0) coord. The following code fixed it.

Vector3 mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
        mousePos.z = 0;
        this.transform.LookAt(mousePos - player.transform.position);