Sometimes rotation script don't work

Hi!

I have script for rotation. It can normal work, for example, 9 times, but when I start it 10th time - player don’t rotate. At 11th time it work fine again… Can someone tell me why?

RaycastHit turnRayHit;
Vector3 mousePosition;
Rigidbody playerRigidbody;

Start()
{
   playerRigidbody = GetComponentInParent<Rigidbody>();
}
void Update()
{
    if (Input.GetKeyUp(KeyCode.Mouse0))
    {
        GetMousePosition();
        Turn();            
    }
}

void GetMousePosition()
{
    Ray turnRay = Camera.main.ScreenPointToRay(Input.mousePosition); 
    if (Physics.Raycast(turnRay, out turnRayHit, 1000))
    {
        mousePosition = turnRayHit.point - transform.position;
        Debug.DrawLine(transform.position, mousePosition, Color.red, 2f);
    }
}

void Turn()
{        
        mousePosition.y = 0f;           
        Quaternion newRotation = Quaternion.LookRotation(mousePosition);           
        playerRigidbody.rotation = newRotation;        
}

When you shoot a ray it only triggers when it touches something that has a collider. So when you click somewhere and there is no object with collider the object will not rotate.

Well, when I click second time on same position, rotation is OK. Also, after rotation player shooting at “mousePosition”, and bullet fly exactly at mouse point, even if player don’t rotate.

After Quaternion newRotation… I make some debug:

float angle = Quaternion.Angle(playerRigidbody.transform.rotation, newRotation);
Debug.Log(“Angle:” + angle);

So, when angle!=0 I know, that script has new mousePosition. And I cleary see, that angle, for example, 45 degrees, but there are no rotation :frowning: