Guest User

Untitled

a guest
Apr 9th, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.55 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4.  
  5. public class CPMAPlayer : MonoBehaviour
  6. {
  7.     // Enumerable controller states
  8.     public enum CharacterState
  9.     {
  10.         Idle = 0,
  11.         Walking = 1,
  12.         Trotting = 2,
  13.         Running = 3,
  14.         Jumping = 4
  15.     }
  16.    
  17.     // Camera public bindings
  18.     public Transform playerCamera;
  19.     public Transform playerCameraSmoothing;
  20.    
  21.     // Character state for FSM
  22.     public CharacterState _characterState;
  23.    
  24.     // Controllable status
  25.     public bool isControllable = true;
  26.    
  27.     // Controller public bindings
  28.     public CharacterController playerController;
  29.     public Transform playerTransform;
  30.    
  31.     // Position and sensitivity settings
  32.     public float viewOffset = 0.6f;
  33.     public float xMouseSensitivity = 30.0f;
  34.     public float yMouseSensitivity = 30.0f;
  35.    
  36.     // Frame occuring variables variables
  37.     public float gravity = 20.0f;
  38.     public float friction = 6.0f;
  39.     public float jumpForce = 8.0f;
  40.     public float moveScale = 1.0f;
  41.    
  42.     // Movement physics variables
  43.     public float forwardSpeed = 7.0f;
  44.     public float forwardAcceleration = 14.0f;
  45.     public float strafeSpeed = 7.0f;
  46.     public float strafeAcceleration = 14.0f;
  47.    
  48.     // Friction and assertion variables
  49.     public float groundDamping = 10.0f;
  50.     public float airAcceleration = 2.0f;
  51.     public float airDamping = 2.0f;
  52.     public float airControl = 0.3f;
  53.    
  54.     // Command scale
  55.     public float scale = 1.0f;
  56.    
  57.     // Grounded state
  58.     private bool grounded = false;
  59.    
  60.     // Audio options
  61.     public AudioClip[] jumpSounds;
  62.    
  63.     // Camera rotationals
  64.     private float rotationX = 0.0f;
  65.     private float rotationY = 0.0f;
  66.     public float dt = 0.0f;
  67.     public GUIStyle style;
  68.    
  69.     // Move direction
  70.     private Vector3 moveDirection = Vector3.zero;
  71.     private Vector3 moveDirectionNorm = Vector3.zero;
  72.    
  73.     // Velocity stoage
  74.     private Vector3 playerVelocity = Vector3.zero;
  75.     private float playerTopVelocity = 0.0f;
  76.    
  77.     // Grounding
  78.     private bool playerGrounded = false;
  79.     private float playerLongestFall = 0.0f;
  80.     private float playerStartFall = 0.0f;
  81.     private float playerStopFall = 0.0f;
  82.    
  83.     // Jump queueing
  84.     private bool wishJump = false;
  85.    
  86.     // Friction settings
  87.     private float playerFriction = 0.0f;
  88.     private float fps = 0.0f;
  89.     private float frameCount = 0.0f;
  90.     private float fpsDisplayRate = 4.0f;
  91.    
  92.     // Cursor settings
  93.     private bool cursorLocked = false;
  94.    
  95.     // Contains the commands the user wishes upon the character
  96.     class Cmd {
  97.         public float playerForward;
  98.         public float playerRight;
  99.         public float playerUp;
  100.     }
  101.    
  102.     // Cmd had a child and named it cmd
  103.     private Cmd cmd;
  104.    
  105.     // Player commands, stores wish commands that the player asks for (Forward, back, jump, etc)
  106.     private bool isDead = false;
  107.    
  108.     // Spawn posiiton and rotation
  109.     private Vector3 playerSpawnPos = Vector3.zero;
  110.     private Quaternion playerSpawnRot;
  111.    
  112.     //HudDisplay on Canvas
  113.     public Text txt;
  114.     private string hudInfo;
  115.     public Text txt2;
  116.     private string hudInfo2;
  117.  
  118.     public int distance = 0;
  119.     public float timePlayed = 0;
  120.    
  121.     // Execute when our scene loads
  122.     void Awake ()
  123.     {
  124.     }
  125.    
  126.     // Use this for initialization
  127.     void Start ()
  128.     {
  129.         xMouseSensitivity = GameController.gameController.GetMouseSensetivity().x;
  130.         yMouseSensitivity = GameController.gameController.GetMouseSensetivity().y;
  131.        
  132.        
  133.         // Sets the player animation to idle on start
  134.         _characterState = CharacterState.Idle;
  135.        
  136.         playerController = this.gameObject.GetComponent<CharacterController>();
  137.         playerTransform = this.transform;
  138.        
  139.         Debug.Log ("Cursor should be hidden.");
  140.         // Fuck the cursor
  141.         Screen.showCursor = false;
  142.         Screen.lockCursor = true;
  143.        
  144.         // Measure user command "wish" force
  145.         cmd = new Cmd();
  146.     }
  147.    
  148.     // Camera updates
  149.     void syncCameraController()
  150.     {
  151.        
  152.     }
  153.    
  154.     void OnGUI()
  155.     {
  156.         GUI.Label(new Rect(0, 0, 400, 100), "FPS: " + fps, style);
  157.         var ups = playerController.velocity;
  158.         ups.y = 0;
  159.        
  160.         hudInfo =  Mathf.Round(ups.magnitude * 100) / 100 + "\n"
  161.             + Mathf.Round(playerTopVelocity * 100) / 100;
  162.         txt.text=hudInfo;
  163.  
  164.         hudInfo2 = Mathf.RoundToInt(timePlayed) + " s\n"
  165.             + Mathf.RoundToInt(distance / 100) + " m";
  166.         txt2.text=hudInfo2;
  167.         //GUI.Label(new Rect(0, 30, 400, 100), "Top Speed: " + Mathf.Round(playerTopVelocity * 100) / 100 + "ups", style);
  168.     }
  169.    
  170.     // Update is called once per frame 
  171.     void Update()
  172.     {
  173.         if(isControllable) {
  174.             // Calculate the framerate
  175.             frameCount++;
  176.             dt += Time.deltaTime;
  177.             if (dt > 1.0f / fpsDisplayRate) {
  178.                 fps = Mathf.Round (frameCount / dt);
  179.                 frameCount = 0;
  180.                 dt -= 1.0f / fpsDisplayRate;
  181.             }
  182.            
  183.             // Seriously, fuck the cursor
  184.             if (Screen.lockCursor == false) {
  185.                 // Clicking manually tells the cursor to fuck off
  186.                 if (Input.GetMouseButtonDown (0))
  187.                     Screen.lockCursor = true;
  188.             }
  189.            
  190.             // Get rotation coordinates
  191.             rotationX -= Input.GetAxisRaw ("Mouse Y") * yMouseSensitivity * 0.02f;
  192.             rotationY += Input.GetAxisRaw ("Mouse X") * xMouseSensitivity * 0.02f;
  193.            
  194.             // Clamp the X rotation
  195.             if (rotationX < -90f)
  196.                 rotationX = -90f;
  197.             else if (rotationX > 90f)
  198.                 rotationX = 90f;
  199.            
  200.             // Rotate the controller and camera
  201.             playerTransform.rotation = Quaternion.Euler (0, rotationY, 0); // Rotates the collider
  202.             playerCamera.rotation = Quaternion.Euler (rotationX, rotationY, 0); // Rotates the camera
  203.            
  204.             // Set the camera's position to the transform
  205.             playerCamera.position = playerTransform.position;
  206.             playerCamera.position.Set (0, playerTransform.position.y + viewOffset, 0);
  207.            
  208.             // Let's jump motherfucker
  209.             QueueJump ();
  210.            
  211.             // Are we on the ground like a little bitch?
  212.             if (playerController.isGrounded) {
  213.                 playerGrounded = true;
  214.                 GroundMove ();
  215.             }
  216.             // Man-mode, time to fly
  217.             else if (!playerController.isGrounded) {
  218.                 playerGrounded = false;
  219.                 AirMove ();
  220.             }
  221.            
  222.             // Move the controller
  223.             playerController.Move (playerVelocity * Time.deltaTime);
  224.            
  225.             // Determine if this is our top velocity
  226.             if (playerVelocity.magnitude > playerTopVelocity)
  227.                 // Fuck yeah superman
  228.                 playerTopVelocity = playerVelocity.magnitude;
  229.            
  230.            
  231.             // Bind some key to spawn
  232.             if (Input.GetKeyDown ("f") && isDead)
  233.                 // Spawn our shit
  234.                 PlayerSpawn ();
  235.         }
  236.  
  237.         var ups = playerController.velocity;
  238.         ups.y = 0;
  239.         distance += Mathf.RoundToInt(ups.magnitude);
  240.  
  241.         timePlayed += Time.deltaTime;
  242.     }
  243.    
  244.    
  245.     // Are we on the ground?
  246.     bool IsGrounded(){
  247.         float distToGround = playerController.bounds.extents.y;
  248.         // Raycast to find a valid ground distance
  249.         return Physics.Raycast(playerTransform.position, -Vector3.up, distToGround + 0.1f);
  250.     }
  251.    
  252.     // Movement direction based on vertical and horizontal axis
  253.     void SetMovementDir()
  254.     {
  255.         // Forward/back
  256.         cmd.playerForward = Input.GetAxis("Vertical");
  257.         // Right/left
  258.         cmd.playerRight   = Input.GetAxis("Horizontal");
  259.         // Up/down velocity
  260.         cmd.playerUp = playerVelocity.y;
  261.        
  262.         // Debug
  263.         //      Debug.Log ("SetMovementDir() - cmd.playerForward=" + cmd.playerForward + "  cmd.playerRight=" + cmd.playerRight);
  264.     }
  265.    
  266.     // Jump asshole
  267.     void QueueJump()
  268.     {
  269.         // Jump on space key and make sure player isn't jumping already
  270.         if(Input.GetKeyDown(KeyCode.Space) && !wishJump)
  271.             wishJump = true;
  272.         if(Input.GetKeyUp(KeyCode.Space))
  273.             wishJump = false;
  274.         //      Debug.Log ("QueueJump() - wishjump=" + wishJump);
  275.     }
  276.    
  277.     // Air movement
  278.     void AirMove()
  279.     {
  280.         Vector3 wishDirection;
  281.         Vector3 currentVelocity;
  282.         float dynamicAcceleration;
  283.         scale = Time.deltaTime;
  284.        
  285.         // Normalized direction
  286.         SetMovementDir();
  287.        
  288.         // Where we want to go
  289.         wishDirection = new Vector3(cmd.playerRight,0,cmd.playerForward);
  290.        
  291.         // Where we're going
  292.         currentVelocity = new Vector3 (playerVelocity.x, 0, playerVelocity.y);
  293.        
  294.         // Set target direction for the character body to its inital state.
  295.         wishDirection = playerTransform.TransformDirection(wishDirection);
  296.        
  297.         var wishSpeed = wishDirection.magnitude;
  298.         wishSpeed *= forwardSpeed;
  299.        
  300.         //      wishSpeed *= 1.0f * Time.deltaTime;
  301.        
  302.         // CPM: Aircontrol
  303.         var wishSpeed2 = wishSpeed;
  304.        
  305.         // This should just be static
  306.         dynamicAcceleration = airAcceleration;
  307.        
  308.         if(cmd.playerForward == 0.0f && cmd.playerRight != 0.0f)
  309.         {
  310.             if(wishSpeed > strafeSpeed)
  311.             {
  312.                 wishSpeed = strafeSpeed;
  313.                 dynamicAcceleration = strafeAcceleration;
  314.             }
  315.         }
  316.        
  317.         Accelerate(wishDirection, wishSpeed, dynamicAcceleration);
  318.         AirControl(wishDirection, wishSpeed);
  319.        
  320.         // Apply gravity
  321.         playerVelocity.y -= gravity * Time.deltaTime;
  322.        
  323.         // LEGACY MOVEMENT SEE BOTTOM
  324.     }
  325.    
  326.     // How we move in the air
  327.     void AirControl(Vector3 wishDirection, float wishSpeed)
  328.     {
  329.         float zspeed;
  330.         float speed;
  331.         float dot;
  332.         float k;
  333.        
  334.         // Are we tryingo to control movement?
  335.         if (wishSpeed == 0.0f) {
  336.             return;
  337.         }
  338.        
  339.         // Capture y
  340.         zspeed = playerVelocity.y;
  341.        
  342.         playerVelocity.y = 0.0f;
  343.        
  344.         speed = playerVelocity.magnitude;
  345.         playerVelocity.Normalize();
  346.        
  347.         dot = Vector3.Dot(playerVelocity, wishDirection);
  348.         k = 320f;
  349.         k *= airControl * dot * dot * Time.deltaTime;
  350.        
  351.         if(dot <= -1)
  352.         {
  353.             playerVelocity.x = playerVelocity.x * speed + wishDirection.x * k;
  354.             playerVelocity.y = playerVelocity.y * speed + wishDirection.y * k;
  355.             playerVelocity.z = playerVelocity.z * speed + wishDirection.z * k;
  356.            
  357.             playerVelocity.Normalize();
  358.             moveDirectionNorm = playerVelocity;
  359.         }
  360.        
  361.         playerVelocity.x *= speed;
  362.         playerVelocity.y = zspeed; // Note this line
  363.         playerVelocity.z *= speed;
  364.        
  365.     }
  366.    
  367.     // Called every frame when engine knows player is grounded
  368.     void GroundMove()
  369.     {
  370.         Vector3 wishDirection;
  371.         Vector3 wishvel;
  372.        
  373.         //      Debug.Log ("Ground sqrMag: " + playerVelocity.sqrMagnitude + ", Grounded: " + IsGrounded());
  374.        
  375.         // Capture squared velocity value
  376.         float velocitySquared = playerVelocity.sqrMagnitude;
  377.        
  378.         // Set animation state based upon speed
  379.         if (velocitySquared < 51f && velocitySquared >= 25f && IsGrounded ()) {
  380.             _characterState = CharacterState.Trotting;
  381.         } else if (velocitySquared < 25f && velocitySquared > 0.1f && IsGrounded ()) {
  382.             _characterState = CharacterState.Walking;
  383.         }else if (playerVelocity.sqrMagnitude >= 51f && IsGrounded ()){
  384.             _characterState = CharacterState.Running;
  385.         }
  386.        
  387.         // Do not apply friction if the player is queueing up the next jump
  388.         if(!wishJump)
  389.             ApplyFriction(1.0f);
  390.         else
  391.             ApplyFriction(0.0f);
  392.        
  393.         scale = Time.fixedDeltaTime;
  394.        
  395.         SetMovementDir();
  396.        
  397.         wishDirection = new Vector3(cmd.playerRight, 0, cmd.playerForward);
  398.         wishDirection = transform.TransformDirection(wishDirection);
  399.         wishDirection.Normalize();
  400.        
  401.         var wishSpeed = wishDirection.magnitude;
  402.         wishSpeed *= forwardSpeed;
  403.        
  404.         Accelerate(wishDirection, wishSpeed, forwardAcceleration);
  405.        
  406.         // Reset the gravity velocity
  407.         playerVelocity.y = 0.0f;
  408.        
  409.         if(wishJump)
  410.         {
  411.             playerVelocity.y = jumpForce;
  412.             wishJump = false;
  413.             PlayJumpSound();
  414.         }
  415.     }
  416.    
  417.     void ApplyFriction(float t)
  418.     {
  419.         Vector3 velocityVector = playerVelocity;
  420.         float velocityFloat;
  421.         float speed;
  422.         float newSpeed;
  423.         float control;
  424.         float drop = 0.0f;
  425.        
  426.         velocityVector.y = 0.0f;
  427.         speed = velocityVector.magnitude;
  428.        
  429.         if(playerController.isGrounded)
  430.         {
  431.             control = speed < forwardAcceleration ? groundDamping : speed;
  432.             drop = control * friction * Time.deltaTime * t;
  433.         }
  434.        
  435.         newSpeed = speed - drop;
  436.         playerFriction = newSpeed;
  437.         if(newSpeed < 0f)
  438.             newSpeed = 0f;
  439.         if(speed > 0f)
  440.             newSpeed /= speed;
  441.        
  442.         playerVelocity.x *= newSpeed;
  443.         //      playerVelocity.y *= newSpeed;
  444.         playerVelocity.z *= newSpeed;
  445.     }
  446.    
  447.     // Acceleration motor
  448.     void Accelerate(Vector3 wishDirection, float wishSpeed, float dynamicAcceleration)
  449.     {
  450.         float addSpeed;
  451.         float accelerationSpeed;
  452.         float currentSpeed;
  453.        
  454.         currentSpeed = Vector3.Dot(playerVelocity, wishDirection);
  455.         addSpeed = wishSpeed - currentSpeed;
  456.         if(addSpeed <= 0.0f)
  457.             return;
  458.         accelerationSpeed = dynamicAcceleration * Time.deltaTime * wishSpeed;
  459.         if(accelerationSpeed > addSpeed)
  460.             accelerationSpeed = addSpeed;
  461.        
  462.         playerVelocity.x += accelerationSpeed * wishDirection.x;
  463.         playerVelocity.z += accelerationSpeed * wishDirection.z;
  464.     }
  465.    
  466.    
  467.     void PlayJumpSound()
  468.     {
  469.         //soundController.PlaySoundByIndex(0,transform.position);
  470.         //GetComponent<AudioSource>().clip = jumpSounds[Random.Range(0, jumpSounds.Length + 1)];
  471.         GetComponent<AudioSource>().PlayOneShot(jumpSounds[Random.Range(0, jumpSounds.Length)]);
  472.     }
  473.    
  474.     void PlayerExplode()
  475.     {
  476.         isDead = true;
  477.     }
  478.    
  479.     void PlayerSpawn()
  480.     {
  481.         //      playerTransform.position = playerSpawnPos;
  482.         //      playerCamera.rotation = playerSpawnRot;
  483.         rotationX = 0.0f;
  484.         rotationY = 0.0f;
  485.         playerVelocity = Vector3.zero;
  486.         isDead = false;
  487.     }
  488.    
  489. }
Add Comment
Please, Sign In to add comment