Player's weapon flips when he turns about the x-axis

I have a player that has the ability to rotate on the x-axis (imagine him falling on his face). The gun he carries is supposed to always be aiming at the mouse cursor. However, when the character is turned 90 degrees in either direction on the x-axis the gun model flips 180 degrees around its own z-axis. The gun still aims at the right location, it’s only the model that flips.

Here is the function that makes the gun aim:

	void Update () {
		transform.LookAt (Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Camera.main.farClipPlane)));
	}

I have to have the gun marked as a child of an empty object, because I imported it from Blender at it has a default rotation of -90 on the x-axis. The empty object itself is a child of the player object. This script is applied to the empty object.

In this image everything is as it should be. The weapon is correctly oriented.

[18819-unity+example+1.png|18819]

In this image you can see the player has turned slightly more than 90 degrees, and is now holding the gun upside-down. When the player’s rotation exceeds 270 degrees the gun flips back over into the correct orientation.

[18820-unity+example+2.png|18820]

This also applies to a rotation about the z-axis.

Is there a solution for this?

1 Answer

1

If you can get hold of the players transform in the gun script, you can orient the LookAt function to point the up direction of the gun in the players up direction like this:

public GameObject player;

void Update () {
    Vector3 lookDirection = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Camera.main.farClipPlane));
       
    transform.LookAt (lookDirection, player.transform.up);
}

That worked thank you :) (I guess that's why I should read the documentation more thoroughly ;)

–

No problem =) Could you please mark the question as answered? Thank you.

–