I’m using the below code to rotate my player to face the mouse position.
It sort of works but how can I constrict it to the Y axis only?
Vector3 direction = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
Quaternion desiredRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, 10 * Time.deltaTime);
1 Answer
1
Hello @ayockel90,
How about you save the value of transform.rotation before changing it and only apply the y to your rotation by making a temporary variable which take x and z from your initial rotation and the desired y:
Quaternion rotation = transform.rotation; // save the current rotation
Quaternion desiredRotation = Quaternion.LookRotation(direction);
Quaternion newRotation = Quaternion.Euler(rotation.eulerAngles.x, desiredRotation.eulerAngles.y, rotation.eulerAngles.z);
transform.rotation = Quaternion.Slerp(rotation, newRotation, 10 * Time.deltaTime); // apply the new rotation
That does help, thanks! Unfortunately it still doesn't seem to work right. It will point my character only down, not towards the mouse position
– ayockel90Hey @ayockel90, What do you mean by "point my character only down"? Have you tried checking the local rotation of your character? maybe your model is facing the wrong direction by default, what you can do if that's the case is to put the rotation script on a gameObject, add another gameObject as child to the one with the script and define the initial rotation of the child in the inspector. If that's not what you wanted then please share more details for us to understand :)
– Cyber_CatsSure, probably best to show you https://imgur.com/a/dBtlWM0 The ship's nose is pointed forward (blue arrow)
– ayockel90@ayockel90 Oh it's 2D I see, but it seems like it's working when the mouse is targeting the area under the ship, try to check the rotation value in the inspector maybe it's a problem with 180/360 degree values
– Cyber_Cats