AeroplaneUserControl2Axis.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using UnityEngine;
  3. using UnityStandardAssets.CrossPlatformInput;
  4. namespace UnityStandardAssets.Vehicles.Aeroplane
  5. {
  6. [RequireComponent(typeof (AeroplaneController))]
  7. public class AeroplaneUserControl2Axis : 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 void Awake()
  15. {
  16. // Set up the reference to the aeroplane controller.
  17. m_Aeroplane = GetComponent<AeroplaneController>();
  18. }
  19. private void FixedUpdate()
  20. {
  21. // Read input for the pitch, yaw, roll and throttle of the aeroplane.
  22. float roll = CrossPlatformInputManager.GetAxis("Horizontal");
  23. float pitch = CrossPlatformInputManager.GetAxis("Vertical");
  24. bool airBrakes = CrossPlatformInputManager.GetButton("Fire1");
  25. // auto throttle up, or down if braking.
  26. float throttle = airBrakes ? -1 : 1;
  27. #if MOBILE_INPUT
  28. AdjustInputForMobileControls(ref roll, ref pitch, ref throttle);
  29. #endif
  30. // Pass the input to the aeroplane
  31. m_Aeroplane.Move(roll, pitch, 0, throttle, airBrakes);
  32. }
  33. private void AdjustInputForMobileControls(ref float roll, ref float pitch, ref float throttle)
  34. {
  35. // because mobile tilt is used for roll and pitch, we help out by
  36. // assuming that a centered level device means the user
  37. // wants to fly straight and level!
  38. // this means on mobile, the input represents the *desired* roll angle of the aeroplane,
  39. // and the roll input is calculated to achieve that.
  40. // whereas on non-mobile, the input directly controls the roll of the aeroplane.
  41. float intendedRollAngle = roll*maxRollAngle*Mathf.Deg2Rad;
  42. float intendedPitchAngle = pitch*maxPitchAngle*Mathf.Deg2Rad;
  43. roll = Mathf.Clamp((intendedRollAngle - m_Aeroplane.RollAngle), -1, 1);
  44. pitch = Mathf.Clamp((intendedPitchAngle - m_Aeroplane.PitchAngle), -1, 1);
  45. // similarly, the throttle axis input is considered to be the desired absolute value, not a relative change to current throttle.
  46. float intendedThrottle = throttle*0.5f + 0.5f;
  47. throttle = Mathf.Clamp(intendedThrottle - m_Aeroplane.Throttle, -1, 1);
  48. }
  49. }
  50. }