Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using System.Collections;
- public class CPMAPlayer : MonoBehaviour
- {
- // Enumerable controller states
- public enum CharacterState
- {
- Idle = 0,
- Walking = 1,
- Trotting = 2,
- Running = 3,
- Jumping = 4
- }
- // Camera public bindings
- public Transform playerCamera;
- public Transform playerCameraSmoothing;
- // Character state for FSM
- public CharacterState _characterState;
- // Controllable status
- public bool isControllable = true;
- // Controller public bindings
- public CharacterController playerController;
- public Transform playerTransform;
- // Position and sensitivity settings
- public float viewOffset = 0.6f;
- public float xMouseSensitivity = 30.0f;
- public float yMouseSensitivity = 30.0f;
- // Frame occuring variables variables
- public float gravity = 20.0f;
- public float friction = 6.0f;
- public float jumpForce = 8.0f;
- public float moveScale = 1.0f;
- // Movement physics variables
- public float forwardSpeed = 7.0f;
- public float forwardAcceleration = 14.0f;
- public float strafeSpeed = 7.0f;
- public float strafeAcceleration = 14.0f;
- // Friction and assertion variables
- public float groundDamping = 10.0f;
- public float airAcceleration = 2.0f;
- public float airDamping = 2.0f;
- public float airControl = 0.3f;
- // Command scale
- public float scale = 1.0f;
- // Grounded state
- private bool grounded = false;
- // Audio options
- public AudioClip[] jumpSounds;
- // Camera rotationals
- private float rotationX = 0.0f;
- private float rotationY = 0.0f;
- public float dt = 0.0f;
- public GUIStyle style;
- // Move direction
- private Vector3 moveDirection = Vector3.zero;
- private Vector3 moveDirectionNorm = Vector3.zero;
- // Velocity stoage
- private Vector3 playerVelocity = Vector3.zero;
- private float playerTopVelocity = 0.0f;
- // Grounding
- private bool playerGrounded = false;
- private float playerLongestFall = 0.0f;
- private float playerStartFall = 0.0f;
- private float playerStopFall = 0.0f;
- // Jump queueing
- private bool wishJump = false;
- // Friction settings
- private float playerFriction = 0.0f;
- private float fps = 0.0f;
- private float frameCount = 0.0f;
- private float fpsDisplayRate = 4.0f;
- // Cursor settings
- private bool cursorLocked = false;
- // Contains the commands the user wishes upon the character
- class Cmd {
- public float playerForward;
- public float playerRight;
- public float playerUp;
- }
- // Cmd had a child and named it cmd
- private Cmd cmd;
- // Player commands, stores wish commands that the player asks for (Forward, back, jump, etc)
- private bool isDead = false;
- // Spawn posiiton and rotation
- private Vector3 playerSpawnPos = Vector3.zero;
- private Quaternion playerSpawnRot;
- //HudDisplay on Canvas
- public Text txt;
- private string hudInfo;
- public Text txt2;
- private string hudInfo2;
- public int distance = 0;
- public float timePlayed = 0;
- // Execute when our scene loads
- void Awake ()
- {
- }
- // Use this for initialization
- void Start ()
- {
- xMouseSensitivity = GameController.gameController.GetMouseSensetivity().x;
- yMouseSensitivity = GameController.gameController.GetMouseSensetivity().y;
- // Sets the player animation to idle on start
- _characterState = CharacterState.Idle;
- playerController = this.gameObject.GetComponent<CharacterController>();
- playerTransform = this.transform;
- Debug.Log ("Cursor should be hidden.");
- // Fuck the cursor
- Screen.showCursor = false;
- Screen.lockCursor = true;
- // Measure user command "wish" force
- cmd = new Cmd();
- }
- // Camera updates
- void syncCameraController()
- {
- }
- void OnGUI()
- {
- GUI.Label(new Rect(0, 0, 400, 100), "FPS: " + fps, style);
- var ups = playerController.velocity;
- ups.y = 0;
- hudInfo = Mathf.Round(ups.magnitude * 100) / 100 + "\n"
- + Mathf.Round(playerTopVelocity * 100) / 100;
- txt.text=hudInfo;
- hudInfo2 = Mathf.RoundToInt(timePlayed) + " s\n"
- + Mathf.RoundToInt(distance / 100) + " m";
- txt2.text=hudInfo2;
- //GUI.Label(new Rect(0, 30, 400, 100), "Top Speed: " + Mathf.Round(playerTopVelocity * 100) / 100 + "ups", style);
- }
- // Update is called once per frame
- void Update()
- {
- if(isControllable) {
- // Calculate the framerate
- frameCount++;
- dt += Time.deltaTime;
- if (dt > 1.0f / fpsDisplayRate) {
- fps = Mathf.Round (frameCount / dt);
- frameCount = 0;
- dt -= 1.0f / fpsDisplayRate;
- }
- // Seriously, fuck the cursor
- if (Screen.lockCursor == false) {
- // Clicking manually tells the cursor to fuck off
- if (Input.GetMouseButtonDown (0))
- Screen.lockCursor = true;
- }
- // Get rotation coordinates
- rotationX -= Input.GetAxisRaw ("Mouse Y") * yMouseSensitivity * 0.02f;
- rotationY += Input.GetAxisRaw ("Mouse X") * xMouseSensitivity * 0.02f;
- // Clamp the X rotation
- if (rotationX < -90f)
- rotationX = -90f;
- else if (rotationX > 90f)
- rotationX = 90f;
- // Rotate the controller and camera
- playerTransform.rotation = Quaternion.Euler (0, rotationY, 0); // Rotates the collider
- playerCamera.rotation = Quaternion.Euler (rotationX, rotationY, 0); // Rotates the camera
- // Set the camera's position to the transform
- playerCamera.position = playerTransform.position;
- playerCamera.position.Set (0, playerTransform.position.y + viewOffset, 0);
- // Let's jump motherfucker
- QueueJump ();
- // Are we on the ground like a little bitch?
- if (playerController.isGrounded) {
- playerGrounded = true;
- GroundMove ();
- }
- // Man-mode, time to fly
- else if (!playerController.isGrounded) {
- playerGrounded = false;
- AirMove ();
- }
- // Move the controller
- playerController.Move (playerVelocity * Time.deltaTime);
- // Determine if this is our top velocity
- if (playerVelocity.magnitude > playerTopVelocity)
- // Fuck yeah superman
- playerTopVelocity = playerVelocity.magnitude;
- // Bind some key to spawn
- if (Input.GetKeyDown ("f") && isDead)
- // Spawn our shit
- PlayerSpawn ();
- }
- var ups = playerController.velocity;
- ups.y = 0;
- distance += Mathf.RoundToInt(ups.magnitude);
- timePlayed += Time.deltaTime;
- }
- // Are we on the ground?
- bool IsGrounded(){
- float distToGround = playerController.bounds.extents.y;
- // Raycast to find a valid ground distance
- return Physics.Raycast(playerTransform.position, -Vector3.up, distToGround + 0.1f);
- }
- // Movement direction based on vertical and horizontal axis
- void SetMovementDir()
- {
- // Forward/back
- cmd.playerForward = Input.GetAxis("Vertical");
- // Right/left
- cmd.playerRight = Input.GetAxis("Horizontal");
- // Up/down velocity
- cmd.playerUp = playerVelocity.y;
- // Debug
- // Debug.Log ("SetMovementDir() - cmd.playerForward=" + cmd.playerForward + " cmd.playerRight=" + cmd.playerRight);
- }
- // Jump asshole
- void QueueJump()
- {
- // Jump on space key and make sure player isn't jumping already
- if(Input.GetKeyDown(KeyCode.Space) && !wishJump)
- wishJump = true;
- if(Input.GetKeyUp(KeyCode.Space))
- wishJump = false;
- // Debug.Log ("QueueJump() - wishjump=" + wishJump);
- }
- // Air movement
- void AirMove()
- {
- Vector3 wishDirection;
- Vector3 currentVelocity;
- float dynamicAcceleration;
- scale = Time.deltaTime;
- // Normalized direction
- SetMovementDir();
- // Where we want to go
- wishDirection = new Vector3(cmd.playerRight,0,cmd.playerForward);
- // Where we're going
- currentVelocity = new Vector3 (playerVelocity.x, 0, playerVelocity.y);
- // Set target direction for the character body to its inital state.
- wishDirection = playerTransform.TransformDirection(wishDirection);
- var wishSpeed = wishDirection.magnitude;
- wishSpeed *= forwardSpeed;
- // wishSpeed *= 1.0f * Time.deltaTime;
- // CPM: Aircontrol
- var wishSpeed2 = wishSpeed;
- // This should just be static
- dynamicAcceleration = airAcceleration;
- if(cmd.playerForward == 0.0f && cmd.playerRight != 0.0f)
- {
- if(wishSpeed > strafeSpeed)
- {
- wishSpeed = strafeSpeed;
- dynamicAcceleration = strafeAcceleration;
- }
- }
- Accelerate(wishDirection, wishSpeed, dynamicAcceleration);
- AirControl(wishDirection, wishSpeed);
- // Apply gravity
- playerVelocity.y -= gravity * Time.deltaTime;
- // LEGACY MOVEMENT SEE BOTTOM
- }
- // How we move in the air
- void AirControl(Vector3 wishDirection, float wishSpeed)
- {
- float zspeed;
- float speed;
- float dot;
- float k;
- // Are we tryingo to control movement?
- if (wishSpeed == 0.0f) {
- return;
- }
- // Capture y
- zspeed = playerVelocity.y;
- playerVelocity.y = 0.0f;
- speed = playerVelocity.magnitude;
- playerVelocity.Normalize();
- dot = Vector3.Dot(playerVelocity, wishDirection);
- k = 320f;
- k *= airControl * dot * dot * Time.deltaTime;
- if(dot <= -1)
- {
- playerVelocity.x = playerVelocity.x * speed + wishDirection.x * k;
- playerVelocity.y = playerVelocity.y * speed + wishDirection.y * k;
- playerVelocity.z = playerVelocity.z * speed + wishDirection.z * k;
- playerVelocity.Normalize();
- moveDirectionNorm = playerVelocity;
- }
- playerVelocity.x *= speed;
- playerVelocity.y = zspeed; // Note this line
- playerVelocity.z *= speed;
- }
- // Called every frame when engine knows player is grounded
- void GroundMove()
- {
- Vector3 wishDirection;
- Vector3 wishvel;
- // Debug.Log ("Ground sqrMag: " + playerVelocity.sqrMagnitude + ", Grounded: " + IsGrounded());
- // Capture squared velocity value
- float velocitySquared = playerVelocity.sqrMagnitude;
- // Set animation state based upon speed
- if (velocitySquared < 51f && velocitySquared >= 25f && IsGrounded ()) {
- _characterState = CharacterState.Trotting;
- } else if (velocitySquared < 25f && velocitySquared > 0.1f && IsGrounded ()) {
- _characterState = CharacterState.Walking;
- }else if (playerVelocity.sqrMagnitude >= 51f && IsGrounded ()){
- _characterState = CharacterState.Running;
- }
- // Do not apply friction if the player is queueing up the next jump
- if(!wishJump)
- ApplyFriction(1.0f);
- else
- ApplyFriction(0.0f);
- scale = Time.fixedDeltaTime;
- SetMovementDir();
- wishDirection = new Vector3(cmd.playerRight, 0, cmd.playerForward);
- wishDirection = transform.TransformDirection(wishDirection);
- wishDirection.Normalize();
- var wishSpeed = wishDirection.magnitude;
- wishSpeed *= forwardSpeed;
- Accelerate(wishDirection, wishSpeed, forwardAcceleration);
- // Reset the gravity velocity
- playerVelocity.y = 0.0f;
- if(wishJump)
- {
- playerVelocity.y = jumpForce;
- wishJump = false;
- PlayJumpSound();
- }
- }
- void ApplyFriction(float t)
- {
- Vector3 velocityVector = playerVelocity;
- float velocityFloat;
- float speed;
- float newSpeed;
- float control;
- float drop = 0.0f;
- velocityVector.y = 0.0f;
- speed = velocityVector.magnitude;
- if(playerController.isGrounded)
- {
- control = speed < forwardAcceleration ? groundDamping : speed;
- drop = control * friction * Time.deltaTime * t;
- }
- newSpeed = speed - drop;
- playerFriction = newSpeed;
- if(newSpeed < 0f)
- newSpeed = 0f;
- if(speed > 0f)
- newSpeed /= speed;
- playerVelocity.x *= newSpeed;
- // playerVelocity.y *= newSpeed;
- playerVelocity.z *= newSpeed;
- }
- // Acceleration motor
- void Accelerate(Vector3 wishDirection, float wishSpeed, float dynamicAcceleration)
- {
- float addSpeed;
- float accelerationSpeed;
- float currentSpeed;
- currentSpeed = Vector3.Dot(playerVelocity, wishDirection);
- addSpeed = wishSpeed - currentSpeed;
- if(addSpeed <= 0.0f)
- return;
- accelerationSpeed = dynamicAcceleration * Time.deltaTime * wishSpeed;
- if(accelerationSpeed > addSpeed)
- accelerationSpeed = addSpeed;
- playerVelocity.x += accelerationSpeed * wishDirection.x;
- playerVelocity.z += accelerationSpeed * wishDirection.z;
- }
- void PlayJumpSound()
- {
- //soundController.PlaySoundByIndex(0,transform.position);
- //GetComponent<AudioSource>().clip = jumpSounds[Random.Range(0, jumpSounds.Length + 1)];
- GetComponent<AudioSource>().PlayOneShot(jumpSounds[Random.Range(0, jumpSounds.Length)]);
- }
- void PlayerExplode()
- {
- isDead = true;
- }
- void PlayerSpawn()
- {
- // playerTransform.position = playerSpawnPos;
- // playerCamera.rotation = playerSpawnRot;
- rotationX = 0.0f;
- rotationY = 0.0f;
- playerVelocity = Vector3.zero;
- isDead = false;
- }
- }
Add Comment
Please, Sign In to add comment