Rotate spaceship based on cursor and QE keys
Good evening community, I'm newbie in Unity and I'm just learning and playing with my code. I would like to understand quaternions and I was stucked on simple thing. I searched on Internet (forums, youtube, ...) and no working answer.
I would like to make spaceship moving and rotating like Elite Dangerous game. It means. WS keys are moving towards and backwards, AD keys are moving left and right. Moving is working well during rotating. QE keys are roll, and mouseXY for pitch and yaw. Everything works good, but when I rotate myself on Z axis (QE key), mouse not working as I expected. When Z is 0, X is horizontal, Y is vertical, but when I rotate Z for example 90°, X is vertical and Y is horinzotal (bad). Can you, please, help me, how to fix it? Sorry for my english.
My code:
[SerializeField] private Camera _Camera = null;
private float _MouseX;
private float _MouseY;
private float _CurrentRotationX = 0;
private float _CurrentRotationY = 0;
[SerializeField] private float _CameraRotationSpeed = 100f;
private void Update() {
_MouseX = Input.GetAxis("Mouse X");
_MouseY = Input.GetAxis("Mouse Y");
float cameraSpeed = Time.deltaTime * _CameraRotationSpeed;
_CurrentRotationX -= _MouseY * cameraSpeed;
_CurrentRotationY += _MouseX * cameraSpeed;
// Roll
if (Input.GetKey(KeyCode.Q)) {
_CurrentRotationZ += 20f * Time.deltaTime;
}
if (Input.GetKey(KeyCode.E)) {
_CurrentRotationZ -= 20f * Time.deltaTime;
}
_Camera.transform.rotation = Quaternion.Euler(_CurrentRotationX, _CurrentRotationY, _CurrentRotationZ);
}
Thank you for your help.
Your answer
![](https://koobas.hobune.stream/wayback/20220613054453im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Cancel out the steering rotation returned from a wheel colliders .GetWorldPose(out pos, out rot); 1 Answer
How to limit only one axis rotation? c# 1 Answer
How can I fix rotation of Z axis to 0? 0 Answers
Draw a ray from a gamobject and keep direction of the ray relative to the gameobjects rotation. 1 Answer