I want to make the player face the cursor in a 3d game, to do so I added this code to the player
void Update()
{
Vector3 objectPos = cam.WorldToScreenPoint(transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 90- angle, 0));
}
this worked when the camera is facing the player but as turn around the player it does not follow the cursor anymore then when I stop ( for example the camera now is behind the player or at the left) the player rotates facing wrong position.
CodePudding user response:
You need to add the cameras rotation to the calculation of the final rotation.
[SerializeField] Camera cam;
[SerializeField] Vector3 rotOffset;
void Update()
{
Vector3 objectPos = cam.WorldToScreenPoint(transform.position);
Vector2 mousePos = Input.mousePosition;
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = cam.transform.rotation * Quaternion.Euler(new Vector3(0, 0, angle)) * Quaternion.Euler(rotOffset);
}
I've extracted your initial rotation offset into a separate variable. You might have to play with it to get the orientation right again and probably change the axis that angle
is affecting.
Also take note that Quaternion multiplication takes order of operation into account. Only switch it if the rotation is completely wrong.
CodePudding user response:
the Solution was that I needed to add the Camera angle of the y axe to the 90 deg offset like so :
transform.rotation = Quaternion.Euler(new Vector3(0, (cam.transform.eulerAngles.y 90)-angle, 0)) ;
now the player is always facing the cursor even when I turn around the player