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;
}
}
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.
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:
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.