- Home /
managing rotation of Turret on two axis
Hi. i'm a beginner developer. My question is how would I go about doing this? i'v found an script on internet and modified for my purpose.
i have a cube(player) with a rectangular cube child(gun).
on the player object i attached two script. a PlayerManager and a PlayerYRotation. the PlayerYRotation would do rotating player towards target(nearest enemy) only on y axis automatically. on the gun obj i attached one script GunZRotation and it would do the rotating the gun only on world z axis based on user mouse position on screen.
if i disable GunZRotation, PlayerYRotation will do its job on rotating towards target on y axis. but if i enable GunZRotation, GunZRotation will do it's jub(rotate it up and down base on mouse position) but no matter what, it's like turret freezed on y axis. doesn't face target on y axis. how can i make them both to work together? maybe there should be one method for both of them, i don't know. thanks in advance. here is the PlayerYRotation script:
     void RotationOnYAxis()
     {
         Vector3 direction = (target.position - transform.position).normalized;
         Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
         transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * yRotationSpeed);
     }
and GunZRotation Script:
     void Update()
     {
         RotationOnZAxis();
     }
 
     void RotationOnZAxis()
     {
         if (Input.GetMouseButton(0))
         {
             Vector3 touch = Input.mousePosition;
             Vector3 screen = Camera.main.ScreenToWorldPoint(new Vector3(touch.x, touch.y, Camera.main.nearClipPlane + 5.0f));
 
             Vector3 direction = (screen - transform.position).normalized;
             Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, direction.y, 0));
             transform.rotation = lookRotation;
         }
     }
Answer by rh_galaxy · Feb 07, 2020 at 01:29 PM
You should set transform.rotation only once with the combined Z and Y rotations, or else you will overwrite the first one with the second one. I think you just multiply the two Quaternion together to achieve that.
Your answer
 
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Strange rotation pattern. 0 Answers
How can I rotate an object without moving it up or down? 0 Answers
What´s wrong with my rotation function? 0 Answers
How to reset child object's rotation without changing parent's 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                