AeroplaneUserControl4Axis.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using UnityEngine;
  3. using UnityStandardAssets.CrossPlatformInput;
  4. namespace UnityStandardAssets.Vehicles.Aeroplane
  5. {
  6. [RequireComponent(typeof (AeroplaneController))]
  7. public class AeroplaneUserControl4Axis : MonoBehaviour
  8. {
  9. // these max angles are only used on mobile, due to the way pitch and roll input are handled
  10. public float maxRollAngle = 80;
  11. public float maxPitchAngle = 80;
  12. // reference to the aeroplane that we're controlling
  13. private AeroplaneController m_Aeroplane;
  14. private float m_Throttle;
  15. private bool m_AirBrakes;
  16. private float m_Yaw;
  17. private void Awake()
  18. {
  19. // Set up the reference to the aeroplane controller.
  20. m_Aeroplane = GetComponent<AeroplaneController>();
  21. }
  22. private void FixedUpdate()
  23. {
  24. // Read input for the pitch, yaw, roll and throttle of the aeroplane.
  25. float roll = CrossPlatformInputManager.GetAxis("Mouse X");
  26. float pitch = CrossPlatformInputManager.GetAxis("Mouse Y");
  27. m_AirBrakes = CrossPlatformInputManager.GetButton("Fire1");
  28. m_Yaw = CrossPlatformInputManager.GetAxis("Horizontal");
  29. m_Throttle = CrossPlatformInputManager.GetAxis("Vertical");
  30. #if MOBILE_INPUT
  31. AdjustInputForMobileControls(ref roll, ref pitch, ref m_Throttle);
  32. #endif
  33. // Pass the input to the aeroplane
  34. m_Aeroplane.Move(roll, pitch, m_Yaw, m_Throttle, m_AirBrakes);
  35. }
  36. private void AdjustInputForMobileControls(ref float roll, ref float pitch, ref float throttle)
  37. {
  38. // because mobile tilt is used for roll and pitch, we help out by
  39. // assuming that a centered level device means the user
  40. // wants to fly straight and level!
  41. // this means on mobile, the input represents the *desired* roll angle of the aeroplane,
  42. // and the roll input is calculated to achieve that.
  43. // whereas on non-mobile, the input directly controls the roll of the aeroplane.
  44. float intendedRollAngle = roll*maxRollAngle*Mathf.Deg2Rad;
  45. float intendedPitchAngle = pitch*maxPitchAngle*Mathf.Deg2Rad;
  46. roll = Mathf.Clamp((intendedRollAngle - m_Aeroplane.RollAngle), -1, 1);
  47. pitch = Mathf.Clamp((intendedPitchAngle - m_Aeroplane.PitchAngle), -1, 1);
  48. }
  49. }
  50. }