Advertisement
Guest User

Vp_FPInput (Cinput Version) - Cinput for UFPS

a guest
Jul 5th, 2015
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.05 KB | None | 0 0
  1. /////////////////////////////////////////////////////////////////////////////////
  2. //
  3. //  vp_FPInput.cs
  4. //  © VisionPunk. All Rights Reserved.
  5. //  https://twitter.com/VisionPunk
  6. //  http://www.visionpunk.com
  7. //
  8. //  description:    a script to collect all mouse and keyboard input for first person
  9. //                  controls in one place
  10. //
  11. /////////////////////////////////////////////////////////////////////////////////
  12.  
  13. using UnityEngine;
  14. using System.Collections.Generic;
  15.  
  16. public class vp_FPInput : vp_Component
  17. {
  18.  
  19.     // mouse look
  20.     public Vector2 MouseLookSensitivity = new Vector2(5.0f, 5.0f);
  21.     public int MouseLookSmoothSteps = 10;               // allowed range: 1-20
  22.     public float MouseLookSmoothWeight = 0.5f;          // allowed range: 0.0f - 1.0f
  23.     public bool MouseLookAcceleration = false;
  24.     public float MouseLookAccelerationThreshold = 0.4f;
  25.     public bool MouseLookInvert = false;
  26.     protected Vector2 m_MouseLookSmoothMove = Vector2.zero;     // distance moved since last frame (smoothed and accelerated)
  27.     protected Vector2 m_MouseLookRawMove = Vector2.zero;        // distance moved since last frame (raw unity input)
  28.     protected List<Vector2> m_MouseLookSmoothBuffer = new List<Vector2>();
  29.     protected int m_LastMouseLookFrame = -1;
  30.     protected Vector2 m_CurrentMouseLook = Vector2.zero;
  31.  
  32.     // mouse cursor
  33.     public Rect[] MouseCursorZones = null;          // screen regions where mouse arrow remains visible when clicking. may be set up in the Inspector
  34.     // NOTE: these do not currently get saved to presets (!)
  35.     public bool MouseCursorForced = false;          // when true, the mouse arrow is enabled all over the screen and firing is disabled
  36.     public bool MouseCursorBlocksMouseLook = true;  // if true, mouselook will be disabled while the mouse arrow is visible
  37.     public Vector2 MousePos { get { return m_MousePos; } }
  38.     protected Vector2 m_MousePos = Vector2.zero;    // current mouse position in GUI coordinates (Y flipped)
  39.  
  40.     // move vector
  41.     protected Vector2 m_MoveVector = Vector2.zero;
  42.  
  43.     // misc
  44.     protected bool m_AllowGameplayInput = true;
  45.     public bool AllowGameplayInput
  46.     {
  47.         get {   return m_AllowGameplayInput;    }
  48.         set {   m_AllowGameplayInput = value;   }
  49.     }
  50.  
  51.     protected vp_FPPlayerEventHandler m_FPPlayer = null;
  52.     public vp_FPPlayerEventHandler FPPlayer
  53.     {
  54.         get
  55.         {
  56.             if (m_FPPlayer == null)
  57.                 m_FPPlayer = transform.root.GetComponentInChildren<vp_FPPlayerEventHandler>();
  58.             return m_FPPlayer;
  59.         }
  60.     }
  61.  
  62.  
  63.     /// <summary>
  64.     /// registers this component with the event handler (if any)
  65.     /// </summary>
  66.     protected override void OnEnable()
  67.     {
  68.  
  69.         if (FPPlayer != null)
  70.             FPPlayer.Register(this);
  71.  
  72.     }
  73.  
  74.  
  75.     /// <summary>
  76.     /// unregisters this component from the event handler (if any)
  77.     /// </summary>
  78.     protected override void OnDisable()
  79.     {
  80.         if (FPPlayer != null)
  81.             FPPlayer.Unregister(this);
  82.  
  83.     }
  84.  
  85.    
  86.     /// <summary>
  87.     ///
  88.     /// </summary>
  89.     protected override void Update()
  90.     {
  91.  
  92.         // manage input for GUI
  93.         UpdateCursorLock();
  94.  
  95.         // toggle pausing and abort if paused
  96.         UpdatePause();
  97.        
  98.         if(FPPlayer.Pause.Get() == true)
  99.             return;
  100.  
  101.         // --- NOTE: everything below this line will be disabled on pause! ---
  102.  
  103.         if (!m_AllowGameplayInput)
  104.             return;
  105.        
  106.         // interaction
  107.         InputInteract();
  108.  
  109.         // manage input for moving
  110.         InputMove();
  111.         InputRun();
  112.         InputJump();
  113.         InputCrouch();
  114.  
  115.         // manage input for weapons
  116.         InputAttack();
  117.         InputReload();
  118.         InputSetWeapon();
  119.  
  120.         // manage camera related input
  121.         InputCamera();
  122.     }
  123.    
  124.  
  125.     /// <summary>
  126.     /// handles interaction with the game world
  127.     /// </summary>
  128.     protected virtual void InputInteract()
  129.     {
  130.  
  131.         if(cInput.GetButtonDown("Interact"))
  132.             FPPlayer.Interact.TryStart();
  133.         else
  134.             FPPlayer.Interact.TryStop();
  135.  
  136.     }
  137.  
  138.  
  139.     /// <summary>
  140.     /// move the player forward, backward, left and right
  141.     /// </summary>
  142.     protected virtual void InputMove()
  143.     {
  144.  
  145.         // NOTE: you could also use 'GetAxis', but that would add smoothing
  146.         // to the input from both Ultimate FPS and from Unity, and might
  147.         // require some tweaking in order not to feel laggy
  148.  
  149.         FPPlayer.InputMoveVector.Set(new Vector2(cInput.GetAxisRaw("Horizontal"), cInput.GetAxisRaw("Vertical")));
  150.  
  151.     }
  152.    
  153.  
  154.     /// <summary>
  155.     /// tell the player to enable or disable the 'Run' state.
  156.     /// NOTE: since running is a state, it's not sent to the
  157.     /// controller code (which doesn't know the state names).
  158.     /// instead, the player class is responsible for feeding the
  159.     /// 'Run' state to every affected component.
  160.     /// </summary>
  161.     protected virtual void InputRun()
  162.     {
  163.  
  164.         if (cInput.GetButton("Run"))
  165.             FPPlayer.Run.TryStart();
  166.         else
  167.             FPPlayer.Run.TryStop();
  168.  
  169.     }
  170.  
  171.  
  172.     /// <summary>
  173.     /// ask controller to jump when button is pressed (the current
  174.     /// controller preset determines jump force).
  175.     /// NOTE: if its 'MotorJumpForceHold' is non-zero, this
  176.     /// also makes the controller accumulate jump force until
  177.     /// button release.
  178.     /// </summary>
  179.     protected virtual void InputJump()
  180.     {
  181.  
  182.         // TIP: to find out what determines if 'Jump.TryStart'
  183.         // succeeds and where it is hooked up, search the project
  184.         // for 'CanStart_Jump'
  185.  
  186.         if (cInput.GetButton("Jump"))
  187.             FPPlayer.Jump.TryStart();
  188.         else
  189.             FPPlayer.Jump.Stop();
  190.  
  191.     }
  192.  
  193.  
  194.     /// <summary>
  195.     /// asks the controller to halve the height of its Unity
  196.     /// CharacterController collision capsule while player is
  197.     /// holding the crouch modifier key. this activity will also
  198.     /// typically trigger states on the camera and weapons. note
  199.     /// that getting up again won't always succeed (for example
  200.     /// the player might be crawling through a ventilation shaft
  201.     /// or hiding under a table).
  202.     /// </summary>
  203.     protected virtual void InputCrouch()
  204.     {
  205.  
  206.         // IMPORTANT: using the 'Crouch' activity for crouching
  207.         // ensures that CharacterController (collision) height is only
  208.         // updated when needed. this is important because changing its
  209.         // height every frame will make trigger detection break!
  210.  
  211.         if (cInput.GetButton("Crouch"))
  212.             FPPlayer.Crouch.TryStart();
  213.         else
  214.             FPPlayer.Crouch.TryStop();
  215.  
  216.         // TIP: to find out what determines if 'Crouch.TryStop'
  217.         // succeeds and where it is hooked up, search the project
  218.         // for 'CanStop_Crouch'
  219.  
  220.     }
  221.  
  222.  
  223.     /// <summary>
  224.     /// camera related input
  225.     /// </summary>
  226.     protected virtual void InputCamera()
  227.     {
  228.  
  229.         // zoom / ADS
  230.         if (cInput.GetButton("Zoom"))
  231.             FPPlayer.Zoom.TryStart();
  232.         else
  233.             FPPlayer.Zoom.TryStop();
  234.  
  235.         // toggle 3rd person mode
  236.         if (cInput.GetButtonDown("Toggle3rdPerson"))
  237.             FPPlayer.CameraToggle3rdPerson.Send();
  238.  
  239.     }
  240.  
  241.  
  242.     /// <summary>
  243.     /// broadcasts a message to any listening components telling
  244.     /// them to go into 'attack' mode. vp_FPWeaponShooter uses this
  245.     /// to repeatedly fire the current weapon while the fire button
  246.     /// is being pressed, but it could also be used by, for example,
  247.     /// an animation script to make the player model loop an 'attack
  248.     /// stance' animation.
  249.     /// </summary>
  250.     protected virtual void InputAttack()
  251.     {
  252.  
  253.         // TIP: uncomment this to prevent player from attacking while running
  254.         //if (Player.Run.Active)
  255.         //  return;
  256.  
  257.         // if mouse cursor is visible, an extra click is needed
  258.         // before we can attack
  259.         if (!vp_Utility.LockCursor)
  260.             return;
  261.  
  262.         if (cInput.GetButton("Attack"))
  263.             FPPlayer.Attack.TryStart();
  264.         else
  265.             FPPlayer.Attack.TryStop();
  266.  
  267.     }
  268.  
  269.  
  270.     /// <summary>
  271.     /// when the reload button is pressed, broadcasts a message
  272.     /// to any listening components asking them to reload
  273.     /// NOTE: reload may not succeed due to ammo status etc.
  274.     /// </summary>
  275.     protected virtual void InputReload()
  276.     {
  277.  
  278.         if (cInput.GetButtonDown("Reload"))
  279.             FPPlayer.Reload.TryStart();
  280.        
  281.     }
  282.  
  283.    
  284.     /// <summary>
  285.     /// handles cycling through carried weapons, wielding specific
  286.     /// ones and clearing the current one
  287.     /// </summary>
  288.     protected virtual void InputSetWeapon()
  289.     {
  290.  
  291.         // --- cycle to the next or previous weapon ---
  292.  
  293.         if (cInput.GetButtonDown("Previous Weapon"))
  294.             FPPlayer.SetPrevWeapon.Try();
  295.  
  296.         if (cInput.GetButtonDown("Next Weapon"))
  297.             FPPlayer.SetNextWeapon.Try();
  298.        
  299.         // --- switch to weapon 1-10 by direct button press ---
  300.  
  301.         // comment this out if you don't want this, don't forget to comment it out in the
  302.         // setupcInput.cs script or it will show up in the menu
  303.         if (cInput.GetKeyDown("Weapon 1")) FPPlayer.SetWeapon.TryStart(1);
  304.         if (cInput.GetKeyDown("Weapon 2")) FPPlayer.SetWeapon.TryStart(2);
  305.         if (cInput.GetKeyDown("Weapon 3")) FPPlayer.SetWeapon.TryStart(3);
  306.         if (cInput.GetKeyDown("Weapon 4")) FPPlayer.SetWeapon.TryStart(4);
  307.         if (cInput.GetKeyDown("Weapon 5")) FPPlayer.SetWeapon.TryStart(5);
  308.         if (cInput.GetKeyDown("Weapon 6")) FPPlayer.SetWeapon.TryStart(6);
  309.         if (cInput.GetKeyDown("Weapon 7")) FPPlayer.SetWeapon.TryStart(7);
  310.         if (cInput.GetKeyDown("Weapon 8")) FPPlayer.SetWeapon.TryStart(8);
  311.         if (cInput.GetKeyDown("Weapon 9")) FPPlayer.SetWeapon.TryStart(9);
  312.         if (cInput.GetKeyDown("Weapon 0")) FPPlayer.SetWeapon.TryStart(10);
  313.  
  314.         // --- unwield current weapon by direct button press ---
  315.  
  316.         if (cInput.GetButtonDown("Clear Weapon")) FPPlayer.SetWeapon.TryStart(0);
  317.  
  318.     }
  319.  
  320.  
  321.  
  322.  
  323.     /// <summary>
  324.     /// toggles the game's pause state on / off
  325.     /// </summary>
  326.     protected virtual void UpdatePause()
  327.     {
  328.  
  329.         if(cInput.GetButtonDown("Pause"))
  330.             FPPlayer.Pause.Set(!FPPlayer.Pause.Get());
  331.  
  332.     }
  333.  
  334.  
  335.     /// <summary>
  336.     /// this method handles toggling between mouse pointer and
  337.     /// firing modes. it can be used to deal with screen regions
  338.     /// for button menus, inventory panels et cetera.
  339.     /// NOTE: if your game supports multiple screen resolutions,
  340.     /// make sure your 'MouseCursorZones' are always adapted to
  341.     /// the current resolution. see 'vp_FPSDemo1.Start' for one
  342.     /// example of how to this
  343.     /// </summary>
  344.     protected virtual void UpdateCursorLock()
  345.     {
  346.  
  347.         // store the current mouse position as GUI coordinates
  348.         m_MousePos.x = Input.mousePosition.x;
  349.         m_MousePos.y = (Screen.height - Input.mousePosition.y);
  350.  
  351.         // uncomment this line to print the current mouse position
  352.         //Debug.Log("X: " + (int)m_MousePos.x + ", Y:" + (int)m_MousePos.y);
  353.  
  354.         // if 'ForceCursor' is active, the cursor will always be visible
  355.         // across the whole screen and firing will be disabled
  356.         if (MouseCursorForced)
  357.         {
  358.             vp_Utility.LockCursor = false;
  359.             return;
  360.         }
  361.  
  362.         // see if any of the mouse buttons are being held down
  363.         if (Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2))
  364.         {
  365.  
  366.             // if we have defined mouse cursor zones, check to see if the
  367.             // mouse cursor is inside any of them
  368.             if (MouseCursorZones.Length > 0)
  369.             {
  370.                 foreach (Rect r in MouseCursorZones)
  371.                 {
  372.                     if (r.Contains(m_MousePos))
  373.                     {
  374.                         // mouse is being held down inside a mouse cursor zone, so make
  375.                         // sure the cursor is not locked and don't lock it this frame
  376.                         vp_Utility.LockCursor = false;
  377.                         goto DontLock;
  378.                     }
  379.                 }
  380.             }
  381.  
  382.             // no zones prevent firing the current weapon. hide mouse cursor
  383.             // and lock it at the center of the screen
  384.             vp_Utility.LockCursor = !setupcInput.guiPanelOpen;
  385.  
  386.         }
  387.  
  388.     DontLock:
  389.  
  390.         // if user presses 'ENTER', toggle mouse cursor on / off
  391.         if (cInput.GetButtonUp("Accept 1")
  392.             || cInput.GetButtonUp("Accept 2")
  393.             || cInput.GetButtonUp("Menu"))
  394.                 vp_Utility.LockCursor = !vp_Utility.LockCursor;
  395.  
  396.     }
  397.  
  398.    
  399.     /// <summary>
  400.     /// mouselook implementation with smooth filtering and acceleration
  401.     /// </summary>
  402.     protected virtual Vector2 GetMouseLook()
  403.     {
  404.  
  405.         // don't allow mouselook if we are using the mouse cursor
  406.         if (MouseCursorBlocksMouseLook && !vp_Utility.LockCursor)
  407.             return Vector2.zero;
  408.  
  409.         // only recalculate mouselook once per frame or smoothing will break
  410.         if (m_LastMouseLookFrame == Time.frameCount)
  411.             return m_CurrentMouseLook;
  412.  
  413.         m_LastMouseLookFrame = Time.frameCount;
  414.  
  415.         // --- fetch mouse input ---
  416.  
  417.         m_MouseLookSmoothMove.x = cInput.GetAxisRaw("HorizontalLook") * Time.timeScale;
  418.         m_MouseLookSmoothMove.y = cInput.GetAxisRaw("VerticalLook") * Time.timeScale;
  419.  
  420.         // --- mouse smoothing ---
  421.  
  422.         // make sure the defined smoothing vars are within range
  423.         MouseLookSmoothSteps = Mathf.Clamp(MouseLookSmoothSteps, 1, 20);
  424.         MouseLookSmoothWeight = Mathf.Clamp01(MouseLookSmoothWeight);
  425.  
  426.         // keep mousebuffer at a maximum of (MouseSmoothSteps + 1) values
  427.         while (m_MouseLookSmoothBuffer.Count > MouseLookSmoothSteps)
  428.             m_MouseLookSmoothBuffer.RemoveAt(0);
  429.  
  430.         // add current input to mouse input buffer
  431.         m_MouseLookSmoothBuffer.Add(m_MouseLookSmoothMove);
  432.  
  433.         // calculate mouse smoothing
  434.         float weight = 1;
  435.         Vector2 average = Vector2.zero;
  436.         float averageTotal = 0.0f;
  437.         for (int i = m_MouseLookSmoothBuffer.Count - 1; i > 0; i--)
  438.         {
  439.             average += m_MouseLookSmoothBuffer[i] * weight;
  440.             averageTotal += (1.0f * weight);
  441.             weight *= (MouseLookSmoothWeight / Delta);
  442.         }
  443.  
  444.         // store the averaged input value
  445.         averageTotal = Mathf.Max(1, averageTotal);
  446.         m_CurrentMouseLook = vp_MathUtility.NaNSafeVector2(average / averageTotal);
  447.  
  448.         // --- mouse acceleration ---
  449.  
  450.         float mouseAcceleration = 0.0f;
  451.  
  452.         float accX = Mathf.Abs(m_CurrentMouseLook.x);
  453.         float accY = Mathf.Abs(m_CurrentMouseLook.y);
  454.  
  455.         if (MouseLookAcceleration)
  456.         {
  457.             mouseAcceleration = Mathf.Sqrt((accX * accX) + (accY * accY)) / Delta;
  458.             mouseAcceleration = (mouseAcceleration <= MouseLookAccelerationThreshold) ? 0.0f : mouseAcceleration;
  459.         }
  460.  
  461.         m_CurrentMouseLook.x *= (MouseLookSensitivity.x + mouseAcceleration);
  462.         m_CurrentMouseLook.y *= (MouseLookSensitivity.y + mouseAcceleration);
  463.  
  464.         m_CurrentMouseLook.y = (MouseLookInvert ? m_CurrentMouseLook.y : -m_CurrentMouseLook.y);
  465.  
  466.         return m_CurrentMouseLook;
  467.  
  468.     }
  469.  
  470.  
  471.     /// <summary>
  472.     /// returns the difference in raw (un-smoothed) mouse input
  473.     /// since last frame
  474.     /// </summary>
  475.     protected virtual Vector2 GetMouseLookRaw()
  476.     {
  477.  
  478.         // don't allow mouselook if we are using the mouse cursor
  479.         if (MouseCursorBlocksMouseLook && !vp_Utility.LockCursor)
  480.             return Vector2.zero;
  481.  
  482.         m_MouseLookRawMove.x = cInput.GetAxisRaw("HorizontalLook");
  483.         m_MouseLookRawMove.y = cInput.GetAxisRaw("VerticalLook");
  484.  
  485.         return m_MouseLookRawMove;
  486.  
  487.     }
  488.  
  489.  
  490.     /// <summary>
  491.     /// returns the current horizontal and vertical input vector
  492.     /// </summary>
  493.     protected virtual Vector2 OnValue_InputMoveVector
  494.     {
  495.         get {   return m_MoveVector;    }
  496. #if UNITY_IPHONE || UNITY_ANDROID
  497.         set {   m_MoveVector = ((value.sqrMagnitude > 1) ? value.normalized : value);   }
  498. #else
  499.         set {   m_MoveVector = ((value != Vector2.zero) ? value.normalized : value);    }
  500. #endif
  501.     }
  502.  
  503.  
  504.     /// <summary>
  505.     /// move vector for climbing. this event callback always returns
  506.     /// a value (unlike 'InputMoveVector' which gets disabled during
  507.     /// climbing)
  508.     /// </summary>
  509.     protected virtual float OnValue_InputClimbVector
  510.     {
  511.         get
  512.         {
  513.             return cInput.GetAxisRaw("Vertical");
  514.         }
  515.     }
  516.  
  517.        
  518.     /// <summary>
  519.     /// allows or prevents first person gameplay input. NOTE:
  520.     /// gui (menu) input is still allowed
  521.     /// </summary>
  522.     protected virtual bool OnValue_InputAllowGameplay
  523.     {
  524.         get {   return m_AllowGameplayInput;    }
  525.         set {   m_AllowGameplayInput = value;   }
  526.     }
  527.  
  528.  
  529.     /// <summary>
  530.     /// pauses the game by setting timescale to zero, or unpauses
  531.     /// it by resuming the timescale that was active upon pause.
  532.     /// NOTE: will not work in multiplayer
  533.     /// </summary>
  534.     protected virtual bool OnValue_Pause
  535.     {
  536.         get { return vp_TimeUtility.Paused; }
  537.         set { vp_TimeUtility.Paused = (vp_Gameplay.isMultiplayer ?  false : value); }
  538.     }
  539.  
  540.  
  541.     /// <summary>
  542.     ///
  543.     /// </summary>
  544.     protected virtual bool OnMessage_InputGetButton(string button)
  545.     {
  546.         return cInput.GetButton(button);
  547.     }
  548.  
  549.  
  550.     /// <summary>
  551.     ///
  552.     /// </summary>
  553.     protected virtual bool OnMessage_InputGetButtonUp(string button)
  554.     {
  555.         return cInput.GetButtonUp(button);
  556.     }
  557.  
  558.  
  559.     /// <summary>
  560.     ///
  561.     /// </summary>
  562.     protected virtual bool OnMessage_InputGetButtonDown(string button)
  563.     {
  564.         return cInput.GetButtonDown(button);
  565.     }
  566.  
  567.  
  568.     /// <summary>
  569.     ///
  570.     /// </summary>
  571.     protected virtual Vector2 OnValue_InputSmoothLook
  572.     {
  573.         get
  574.         {
  575.             return GetMouseLook();
  576.         }
  577.     }
  578.  
  579.  
  580.     /// <summary>
  581.     ///
  582.     /// </summary>
  583.     protected virtual Vector2 OnValue_InputRawLook
  584.     {
  585.         get
  586.         {
  587.             return GetMouseLookRaw();
  588.         }
  589.     }
  590.  
  591.  
  592. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement