Advertisement
hamzarmehyar

Untitled

Jun 19th, 2021
980
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.61 KB | None | 0 0
  1. using System;using System;
  2. using Mirror;
  3. using UnityEngine;
  4.  
  5. public class PlayerMovement : MonoBehaviour
  6. {
  7.  #region AssignableObjects
  8.  [Header("AssignableObjects")]
  9.  
  10.  public Transform cameraTransform;
  11.  public Transform orientation;
  12. #endregion
  13.  
  14.  private Rigidbody rb;
  15.  #region Movement
  16.  [Header("Movement")]
  17.  
  18.  public float defaultMovementSpeed = 4500;
  19.  public float maximumSpeed = 20;
  20.  
  21.  public float counterMovement = 0.175f;
  22.  private float threshold = 0.01f;
  23.  public float maxSlopeAngle = 35f;
  24.  #endregion
  25.  
  26.  #region Jumping
  27.  [Header("Jumping")]
  28.  public bool isGrounded;
  29.  public float jumpForce = 550f;
  30.  public LayerMask whatIsGround;
  31.  private bool readyToJump = true;
  32.  private float jumpCooldown = 0.25f;
  33.  #endregion
  34.  #region CrouchAndSlide
  35.  [Header("CrouchAndSlide")]
  36.  private Vector3 playerScale;
  37.  private Vector3 crouchScale = new Vector3(1, 0.5f, 1);
  38.  public float slideSpeed = 450;
  39. #endregion
  40.  bool isJumping, isSprinting, isCrouching;
  41.  #region PrivateVariables
  42.  
  43.  private bool cancellingGrounded;
  44.  float x, y;
  45.  private Vector3 defaultVector = Vector3.up;
  46.  private Vector3 wallDefaultVector;
  47.  private float xAxisRotation;
  48.  private float mouseSensitivity = 50f;
  49.  private float mouseAcceleration = 1f;
  50.  #endregion
  51.  void Awake() {
  52.    rb = GetComponent<Rigidbody>();//since the rigidbody is a component, it can only be return after the object was instanatiated, this assures we get the rigidbody after the obj was instantiated.
  53.  
  54.  }
  55.  
  56.  void Start() {
  57.    initPrivates();
  58.  }
  59. void initPrivates(){
  60.    playerScale =  transform.localScale;
  61.    Cursor.lockState = CursorLockMode.Locked;
  62.    Cursor.visible = false;
  63. }
  64.  private void FixedUpdate() {
  65.    Movement();
  66.  }
  67.  
  68.  private void Update() {
  69.    MyInput(); //gets input
  70.    MouseLook();
  71.  }
  72.  
  73.  private void MyInput() {
  74.    x = Input.GetAxisRaw("Horizontal");
  75.    y = Input.GetAxisRaw("Vertical");
  76.    isJumping = Input.GetButton("Jump");
  77.    isCrouching = Input.GetKey(KeyCode.LeftControl);
  78.    if (Input.GetKeyDown(KeyCode.LeftControl))
  79.      StartCrouch();
  80.    if (Input.GetKeyUp(KeyCode.LeftControl))
  81.      StopCrouch();
  82.  }
  83.  
  84.  private void StartCrouch() {
  85.    transform.localScale = crouchScale;
  86.    transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
  87.    if (rb.velocity.magnitude > 0.5f) {
  88.      if (isGrounded) {
  89.        rb.AddForce(orientation.transform.forward * slideSpeed);
  90.      }
  91.    }
  92.  }
  93.  
  94.  private void StopCrouch() {
  95.    transform.localScale = playerScale;
  96.    transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
  97.  }
  98.  
  99.  private void Movement() {
  100.    rb.AddForce(Vector3.down * Time.deltaTime * 10);
  101.  
  102.    Vector2 magnitude = GetCurrentVelocity();
  103.  
  104.    CounterMove(x, y, magnitude);
  105.  
  106.    if (readyToJump && isJumping) Jump();
  107.  
  108.    if (isCrouching && isGrounded && readyToJump) {
  109.      rb.AddForce(Vector3.down * Time.deltaTime * 3000);
  110.      return;
  111.    }
  112.    LimitMaxSpeed(magnitude);
  113.  
  114.    float multiplier = 1f, multiplierV = 1f;
  115.    if (!isGrounded) {
  116.      multiplier = 0.5f;
  117.      multiplierV = 0.5f;
  118.    }
  119.    if (isGrounded && isCrouching) multiplierV = 0f;
  120.    rb.AddForce(orientation.transform.forward * y * defaultMovementSpeed * Time.deltaTime * multiplier * multiplierV);
  121.    rb.AddForce(orientation.transform.right * x * defaultMovementSpeed * Time.deltaTime * multiplier);
  122.  }
  123.  private void LimitMaxSpeed(Vector2 magnitude){
  124.    if (x > 0 && magnitude.x> maximumSpeed) x = 0;
  125.    if (x < 0 && magnitude.x < -maximumSpeed) x = 0;
  126.    if (y > 0 && magnitude.y > maximumSpeed) y = 0;
  127.    if (y < 0 && magnitude.y< -maximumSpeed) y = 0;
  128.  }
  129.  
  130.  private void Jump() {
  131.    if (isGrounded && readyToJump) {
  132.      readyToJump = false;
  133.      rb.AddForce(Vector2.up * jumpForce * 1.5f);
  134.      rb.AddForce(defaultVector * jumpForce * 0.5f);
  135.      Vector3 vel = rb.velocity;
  136.      if (rb.velocity.y < 0.5f)
  137.        rb.velocity = new Vector3(vel.x, 0, vel.z);
  138.      else if (rb.velocity.y > 0)
  139.        rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
  140.  
  141.      Invoke(nameof(ResetJump), jumpCooldown);
  142.    }
  143.  }
  144.  
  145.  private void ResetJump() {
  146.    readyToJump = true;
  147.  }
  148.  
  149.  private float desiredX;
  150.  private void MouseLook() {
  151.    float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.fixedDeltaTime * mouseAcceleration;
  152.    float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.fixedDeltaTime * mouseAcceleration;
  153.    Vector3 rot = cameraTransform.transform.localRotation.eulerAngles;
  154.    desiredX = rot.y + mouseX;
  155.    xAxisRotation -= mouseY;
  156.    xAxisRotation = Mathf.Clamp(xAxisRotation, -90f, 90f);
  157.    cameraTransform.transform.localRotation = Quaternion.Euler(xAxisRotation, desiredX, 0);
  158.    orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
  159.  }
  160.  
  161.  private void CounterMove(float x, float y, Vector2 magnitude) {
  162.    if (!isGrounded || isJumping) return;
  163.    if (isCrouching) {
  164.      rb.AddForce(defaultMovementSpeed * Time.deltaTime * -rb.velocity.normalized * 0.2f);
  165.      return;
  166.    }
  167.    AddCounterForce(orientation.transform.right,x,magnitude.x);
  168.    AddCounterForce(orientation.transform.forward,y,magnitude.y);  
  169.    if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maximumSpeed) {
  170.      float fallSpeed = rb.velocity.y;
  171.      Vector3 n = rb.velocity.normalized * maximumSpeed;
  172.      rb.velocity = new Vector3(n.x, fallSpeed, n.z);
  173.    }
  174.  }
  175.  void AddCounterForce(Vector3 direction,float axis,float magnitude){
  176.    if (Math.Abs(magnitude) > threshold && Math.Abs(axis) < 0.05f || (magnitude < -threshold && axis > 0) || (magnitude > threshold && axis < 0))
  177.      rb.AddForce(defaultMovementSpeed * direction * Time.deltaTime * -magnitude * counterMovement);
  178.  }
  179.  
  180.  public Vector2 GetCurrentVelocity() {
  181.    float lookAngle = orientation.transform.eulerAngles.y;
  182.    float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
  183.    float u = Mathf.DeltaAngle(lookAngle, moveAngle);
  184.    return new Vector2( rb.velocity.magnitude * Mathf.Cos((90 - u) * Mathf.Deg2Rad),rb.velocity.magnitude * Mathf.Cos(u * Mathf.Deg2Rad));
  185.  
  186.  
  187.  }
  188.  
  189.  private bool IsOnFloor(Vector3 v) {
  190.    float angle = Vector3.Angle(Vector3.up, v);
  191.    return angle < maxSlopeAngle;
  192.  }
  193.  
  194.  private void OnCollisionStay(Collision other) {
  195.    int layer = other.gameObject.layer;
  196.    if (whatIsGround != (whatIsGround | (1 << layer))) return;
  197.    for (int i = 0; i < other.contactCount; i++) {
  198.      Vector3 FloorContact = other.contacts[i].normal;
  199.      if (IsOnFloor(FloorContact)) {
  200.        isGrounded = true;
  201.        cancellingGrounded = false;
  202.        defaultVector = FloorContact;
  203.        CancelInvoke(nameof(StopGrounded));
  204.      }
  205.    }
  206.    float delay = 3f;
  207.    if (!cancellingGrounded) {
  208.      cancellingGrounded = true;
  209.      Invoke(nameof(StopGrounded), Time.deltaTime * delay);
  210.    }
  211.  }
  212.  
  213.  private void StopGrounded() {
  214.    isGrounded = false;
  215.  }
  216.  
  217. }
  218.  
  219. __________________________________________________________________________________
  220.  
  221.  
  222. public class PlayerRaycast :NetworkBehaviour
  223. {
  224.   RaycastHit hit;
  225.  GameObject prevObject;
  226.  EventObject prevEventObject;
  227.  public Camera mainCamera;
  228.  EventObject eventObject;
  229.  void Input(){
  230.  if(Input.GetKeyDown(KeyCode.E))
  231.      {
  232.        Click();
  233.      }
  234.      if(Input.GetKeyUp(KeyCode.E))
  235.      {
  236.        DeClick();
  237.      }
  238.  }
  239.  void Update()
  240.  {
  241.    if(!isLocalPlayer)
  242.      return;
  243.    if (IsLookingAtRaycastableObject()&&!IsPlayerCurrentlyHolding()){
  244.      eventObject=hit.collider.transform.gameObject.GetComponent<EventObject>();
  245.      HighLightCurrentObject();
  246.      TogglePlayerPickUp(false);
  247.     Input();
  248.    }
  249.    if(StoppedLookingAtPreviousObject()){
  250.      DeHighLightPreviousObject();
  251.      TogglePlayerPickUp(true);
  252.      prevObject=null;
  253.    }
  254.    StoreCurrentObject();
  255.  }
  256.  public void Click(){
  257.    eventObject.Click(this.GetComponent<PlayerAuth>());
  258.  }
  259.  public void DeClick(){
  260.    eventObject.DeClick();
  261.  }
  262.  public void HighLightCurrentObject(){
  263.    eventObject.HighLight(true);
  264.  }
  265.  public void DeHighLightPreviousObject(){
  266.    prevEventObject.HighLight(false);
  267.  }
  268.  public void StoreCurrentObject(){
  269.    if(hit.normal!=Vector3.zero)// if we encountered an object before, store it so we can dehighlight it after leaving it
  270.    {
  271.      prevObject=hit.collider.gameObject;
  272.      prevEventObject=eventObject;
  273.    }
  274.  }
  275.  public bool StoppedLookingAtPreviousObject(){
  276.    return (prevObject!=null&&hit.collider!=null&&prevEventObject!=null&&prevObject!=hit.collider.gameObject);
  277.  }
  278.  public bool IsLookingAtRaycastableObject(){
  279.    return Physics.Raycast(mainCamera.transform.position,mainCamera.transform.forward, out hit, 100.0f)&&hit.collider.transform.tag=="Raycastable";
  280.  }
  281.  public bool IsPlayerCurrentlyHolding(){
  282.    return this.GetComponent<RbPickUp>().IsCurrentlyHolding();
  283.  }
  284.  public void TogglePlayerPickUp(bool flag){
  285.    this.GetComponent<RbPickUp>().TogglePickupFeature(flag);
  286.  }
  287. }
  288.  
  289.  
  290. _______________________________---
  291.  
  292. public class ObjectAuthority : NetworkBehaviour
  293. {
  294.  PlayerAuth currentPlayerWithAuth;
  295.  public void GiveAuth(PlayerAuth player){
  296.    if(!hasAuthority&&currentPlayerWithAuth!=null){
  297.      RemoveAuth();
  298.    }
  299.    player.GiveAuthority(this.GetComponent<NetworkIdentity>());
  300.    currentPlayerWithAuth=player;
  301.  }
  302.  public void RemoveAuth(){
  303.    currentPlayerWithAuth.RemoveAuthority(this.GetComponent<NetworkIdentity>());
  304.  }
  305. }
  306.  
  307.  
  308.  
  309. ____________________--
  310.  
  311.  
  312.  
  313.  
  314.  
  315.  
  316.  
  317.  
  318.  
  319.  
  320. public class EventObject: MonoBehaviour
  321. {
  322.  public UnityEvent onClickEvent;
  323.  public UnityEvent deClickEvent;
  324.  public AuthorityEvent takeAuthEvent;
  325.  public UnityEvent onHighlightEvent;
  326.  public UnityEvent onDeHighlightEvent;
  327.  void Awake(){
  328.    if(onClickEvent==null){
  329.      onClickEvent=new UnityEvent();
  330.    }
  331.    if(onHighlightEvent==null){
  332.      onHighlightEvent=new UnityEvent();
  333.    }
  334.    if(onDeHighlightEvent==null){
  335.      onDeHighlightEvent=new UnityEvent();
  336.    }
  337.  }
  338.  public void Click(PlayerAuth playerAuth){
  339.    takeAuthEvent.Invoke(playerAuth);
  340.    onClickEvent.Invoke();
  341.  }
  342.  public void DeClick(){
  343.    deClickEvent.Invoke();
  344.  }
  345.  public void HighLight(bool isHighlighted){
  346.    if(isHighlighted){
  347.      onHighlightEvent.Invoke();
  348.    }
  349.    else{
  350.      onDeHighlightEvent.Invoke();
  351.    }
  352.  }
  353. __________________________________________--
  354. public class RbPickUp : NetworkBehaviour
  355. {
  356.  public string pickableObjectsTag;
  357.  public GameObject pickedObjectGuide;
  358.  
  359.  public PickUpTrigger pickUpTrigger;
  360.  
  361.  public Camera playerCamera;
  362.  [Range(100, 5000)]
  363.  public float throwForce = 1000;
  364.  [Range(0.01f, 1)]
  365.  public float centerizationSpeed = 0.01f;
  366.  GameObject objectBeingPicked;
  367.  Rigidbody objectBeingPickedRigidBody;
  368.  Rigidbody characterController;
  369.  bool isBeingHeld = false;
  370.  bool canPickup = true;
  371.  private void Start()
  372.  {
  373.    characterController = this.GetComponent<Rigidbody>();
  374.  }
  375.  public bool canBePickedUp()
  376.  {
  377.    return (!isBeingHeld && pickUpTrigger.highLightedObject != null&&pickUpTrigger.highLightedObject.CompareTag(pickableObjectsTag));
  378.  }
  379.  void checkInput()
  380.  {
  381.    if (Input.GetKeyDown(KeyCode.E) && canBePickedUp())
  382.    {
  383.      PickUpObject();
  384.    }
  385.    else if (Input.GetKeyDown(KeyCode.E) && isBeingHeld)
  386.    {
  387.      PutDownObject();
  388.    }
  389.    else if (Input.GetMouseButton(1) && isBeingHeld)
  390.    {
  391.      ThrowObject();
  392.    }
  393.  }
  394.  void Update()
  395.  {
  396.    if (canPickup)
  397.    {
  398.      if (objectBeingPicked == null || objectBeingPicked.Equals(null)) //this handles if the object got destroyed while its being held
  399.        isBeingHeld = false;
  400.      checkInput();
  401.      if (isBeingHeld)
  402.      {
  403.        ParentObject();
  404.      }
  405.    }
  406.  }
  407.  
  408.  void ParentObject()
  409.  {
  410.    objectBeingPicked.transform.position =  pickedObjectGuide.transform.position;
  411.    objectBeingPicked.transform.rotation =  pickedObjectGuide.transform.rotation;
  412.  }
  413.  
  414.  #region PickUP
  415.    void PickUpObject(){
  416.    objectBeingPicked = pickUpTrigger.highLightedObject;
  417.    isBeingHeld = true;
  418.    CmdPickUpObject(objectBeingPicked);
  419.    objectBeingPickedRigidBody = objectBeingPicked.GetComponent<Rigidbody>();
  420.    objectBeingPickedRigidBody.Sleep();
  421.    objectBeingPickedRigidBody.useGravity = false;
  422.  }
  423.  [Command]
  424.  void CmdPickUpObject(GameObject objectBeingPicked)
  425.  {
  426.    objectBeingPicked.GetComponent<NetworkIdentity>().AssignClientAuthority(this.GetComponent<NetworkIdentity>().connectionToClient);
  427.    isBeingHeld = true;
  428.    objectBeingPickedRigidBody = objectBeingPicked.GetComponent<Rigidbody>();
  429.    objectBeingPickedRigidBody.Sleep();
  430.    objectBeingPickedRigidBody.useGravity = false;
  431.  }
  432. #endregion
  433.  
  434.  
  435. #region PutDown
  436.  public void putDownOnTriggerExit(Collider col)
  437.  {
  438.    if (col.gameObject == objectBeingPicked)
  439.    {
  440.      PutDownObject();
  441.    }
  442.  
  443.  }
  444.  
  445.   void PutDownObject()
  446.  {
  447.    isBeingHeld = false;
  448.    objectBeingPickedRigidBody.AddForce(characterController.velocity, ForceMode.VelocityChange); //add player's velocity
  449.    objectBeingPickedRigidBody.WakeUp();
  450.    objectBeingPickedRigidBody.useGravity = true;
  451.    CmdPutDownObject(objectBeingPicked);
  452.    objectBeingPicked = null;
  453.    objectBeingPickedRigidBody = null;
  454.  }
  455.  [Command]
  456.  void CmdPutDownObject(GameObject objectBeingPicked)
  457.  {
  458.    isBeingHeld = false;
  459.    Rigidbody objectBeingPickedRigidBody=objectBeingPicked.GetComponent<Rigidbody>();
  460.    objectBeingPickedRigidBody.AddForce(characterController.velocity, ForceMode.VelocityChange);
  461.    objectBeingPicked.transform.SetParent(null);
  462.    objectBeingPickedRigidBody.WakeUp();
  463.    objectBeingPickedRigidBody.useGravity = true;
  464.    objectBeingPicked.GetComponent<NetworkIdentity>().RemoveClientAuthority();
  465.    objectBeingPicked = null;
  466.    objectBeingPickedRigidBody = null;
  467.  }
  468. #endregion
  469.  
  470. #region Throw
  471.  void ThrowObject()
  472.  {
  473.    Vector3 throwDirection = playerCamera.transform.forward * throwForce; //camera's direction
  474.    Vector3 playersVelocity = characterController.velocity; //camera's direction
  475.    objectBeingPickedRigidBody.AddForce(throwDirection, ForceMode.Force); //add player's velocity
  476.    objectBeingPickedRigidBody.AddForce(playersVelocity, ForceMode.VelocityChange); //add player's velocity
  477.    CmdThrowObject();
  478.    PutDownObject();
  479.  }
  480.  [Command]
  481.  void CmdThrowObject()
  482.  {
  483.    Vector3 throwDirection = playerCamera.transform.forward * throwForce; //camera's direction
  484.    Vector3 playersVelocity = characterController.velocity; //camera's direction
  485.    objectBeingPickedRigidBody.AddForce(throwDirection, ForceMode.Force); //add player's velocity
  486.    objectBeingPickedRigidBody.AddForce(playersVelocity, ForceMode.VelocityChange); //add player's velocity
  487.    PutDownObject();
  488.  }
  489.  
  490. #endregion
  491.  
  492.  public void TogglePickupFeature(bool canMove)//todo make a better name
  493.  {
  494.    this.canPickup = canMove;
  495.  }
  496.  public bool IsCurrentlyHolding(){
  497.    return this.isBeingHeld;
  498.  }
  499. }
  500.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement