1. using UnityEngine;
    2. using System.Collections;
    3. [RequireComponent(typeof(CharacterController))]
    4. [AddComponentMenu("Character/Platform Input Controller")]
    5. public class PlatformInputController : MonoBehaviour {
    6. public bool autoRotate = true;
    7. public float maxRotationSpeed = 360;
    8. private CharacterMotor motor ;
    9. // Use this for initialization
    10. void Awake () {
    11. motor = GetComponent<CharacterMotor>();
    12. }
    13. // Update is called once per frame
    14. void Update () {
    15. // Get the input vector from kayboard or analog stick
    16. Vector3 directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
    17. if (directionVector != Vector3.zero) {
    18. // Get the length of the directon vector and then normalize it
    19. // Dividing by the length is cheaper than normalizing when we already have the length anyway
    20. var directionLength = directionVector.magnitude;
    21. directionVector = directionVector / directionLength;
    22. // Make sure the length is no bigger than 1
    23. directionLength = Mathf.Min(1, directionLength);
    24. // Make the input vector more sensitive towards the extremes and less sensitive in the middle
    25. // This makes it easier to control slow speeds when using analog sticks
    26. directionLength = directionLength * directionLength;
    27. // Multiply the normalized direction vector by the modified length
    28. directionVector = directionVector * directionLength;
    29. }
    30. // Rotate the input vector into camera space so up is camera's up and right is camera's right
    31. directionVector = Camera.main.transform.rotation * directionVector;
    32. // Rotate input vector to be perpendicular to character's up vector
    33. var camToCharacterSpace = Quaternion.FromToRotation(-Camera.main.transform.forward, transform.up);
    34. directionVector = (camToCharacterSpace * directionVector);
    35. // Apply the direction to the CharacterMotor
    36. motor.inputMoveDirection = directionVector;
    37. motor.inputJump = Input.GetButton("Jump");
    38. // Set rotation to the move direction
    39. if (autoRotate && directionVector.sqrMagnitude > 0.01) {
    40. Vector3 newForward = ConstantSlerp(
    41. transform.forward,
    42. directionVector,
    43. maxRotationSpeed * Time.deltaTime
    44. );
    45. newForward = ProjectOntoPlane(newForward, transform.up);
    46. transform.rotation = Quaternion.LookRotation(newForward, transform.up);
    47. }
    48. }
    49. Vector3 ProjectOntoPlane (Vector3 v, Vector3 normal) {
    50. return v - Vector3.Project(v, normal);
    51. }
    52. Vector3 ConstantSlerp (Vector3 from, Vector3 to, float angle) {
    53. float value = Mathf.Min(1, angle / Vector3.Angle(from, to));
    54. return Vector3.Slerp(from, to, value);
    55. }
    56. }