Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;using System;
- using Mirror;
- using UnityEngine;
- public class PlayerMovement : MonoBehaviour
- {
- #region AssignableObjects
- [Header("AssignableObjects")]
- public Transform cameraTransform;
- public Transform orientation;
- #endregion
- private Rigidbody rb;
- #region Movement
- [Header("Movement")]
- public float defaultMovementSpeed = 4500;
- public float maximumSpeed = 20;
- public float counterMovement = 0.175f;
- private float threshold = 0.01f;
- public float maxSlopeAngle = 35f;
- #endregion
- #region Jumping
- [Header("Jumping")]
- public bool isGrounded;
- public float jumpForce = 550f;
- public LayerMask whatIsGround;
- private bool readyToJump = true;
- private float jumpCooldown = 0.25f;
- #endregion
- #region CrouchAndSlide
- [Header("CrouchAndSlide")]
- private Vector3 playerScale;
- private Vector3 crouchScale = new Vector3(1, 0.5f, 1);
- public float slideSpeed = 450;
- #endregion
- bool isJumping, isSprinting, isCrouching;
- #region PrivateVariables
- private bool cancellingGrounded;
- float x, y;
- private Vector3 defaultVector = Vector3.up;
- private Vector3 wallDefaultVector;
- private float xAxisRotation;
- private float mouseSensitivity = 50f;
- private float mouseAcceleration = 1f;
- #endregion
- void Awake() {
- 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.
- }
- void Start() {
- initPrivates();
- }
- void initPrivates(){
- playerScale = transform.localScale;
- Cursor.lockState = CursorLockMode.Locked;
- Cursor.visible = false;
- }
- private void FixedUpdate() {
- Movement();
- }
- private void Update() {
- MyInput(); //gets input
- MouseLook();
- }
- private void MyInput() {
- x = Input.GetAxisRaw("Horizontal");
- y = Input.GetAxisRaw("Vertical");
- isJumping = Input.GetButton("Jump");
- isCrouching = Input.GetKey(KeyCode.LeftControl);
- if (Input.GetKeyDown(KeyCode.LeftControl))
- StartCrouch();
- if (Input.GetKeyUp(KeyCode.LeftControl))
- StopCrouch();
- }
- private void StartCrouch() {
- transform.localScale = crouchScale;
- transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
- if (rb.velocity.magnitude > 0.5f) {
- if (isGrounded) {
- rb.AddForce(orientation.transform.forward * slideSpeed);
- }
- }
- }
- private void StopCrouch() {
- transform.localScale = playerScale;
- transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
- }
- private void Movement() {
- rb.AddForce(Vector3.down * Time.deltaTime * 10);
- Vector2 magnitude = GetCurrentVelocity();
- CounterMove(x, y, magnitude);
- if (readyToJump && isJumping) Jump();
- if (isCrouching && isGrounded && readyToJump) {
- rb.AddForce(Vector3.down * Time.deltaTime * 3000);
- return;
- }
- LimitMaxSpeed(magnitude);
- float multiplier = 1f, multiplierV = 1f;
- if (!isGrounded) {
- multiplier = 0.5f;
- multiplierV = 0.5f;
- }
- if (isGrounded && isCrouching) multiplierV = 0f;
- rb.AddForce(orientation.transform.forward * y * defaultMovementSpeed * Time.deltaTime * multiplier * multiplierV);
- rb.AddForce(orientation.transform.right * x * defaultMovementSpeed * Time.deltaTime * multiplier);
- }
- private void LimitMaxSpeed(Vector2 magnitude){
- if (x > 0 && magnitude.x> maximumSpeed) x = 0;
- if (x < 0 && magnitude.x < -maximumSpeed) x = 0;
- if (y > 0 && magnitude.y > maximumSpeed) y = 0;
- if (y < 0 && magnitude.y< -maximumSpeed) y = 0;
- }
- private void Jump() {
- if (isGrounded && readyToJump) {
- readyToJump = false;
- rb.AddForce(Vector2.up * jumpForce * 1.5f);
- rb.AddForce(defaultVector * jumpForce * 0.5f);
- Vector3 vel = rb.velocity;
- if (rb.velocity.y < 0.5f)
- rb.velocity = new Vector3(vel.x, 0, vel.z);
- else if (rb.velocity.y > 0)
- rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
- Invoke(nameof(ResetJump), jumpCooldown);
- }
- }
- private void ResetJump() {
- readyToJump = true;
- }
- private float desiredX;
- private void MouseLook() {
- float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.fixedDeltaTime * mouseAcceleration;
- float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.fixedDeltaTime * mouseAcceleration;
- Vector3 rot = cameraTransform.transform.localRotation.eulerAngles;
- desiredX = rot.y + mouseX;
- xAxisRotation -= mouseY;
- xAxisRotation = Mathf.Clamp(xAxisRotation, -90f, 90f);
- cameraTransform.transform.localRotation = Quaternion.Euler(xAxisRotation, desiredX, 0);
- orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
- }
- private void CounterMove(float x, float y, Vector2 magnitude) {
- if (!isGrounded || isJumping) return;
- if (isCrouching) {
- rb.AddForce(defaultMovementSpeed * Time.deltaTime * -rb.velocity.normalized * 0.2f);
- return;
- }
- AddCounterForce(orientation.transform.right,x,magnitude.x);
- AddCounterForce(orientation.transform.forward,y,magnitude.y);
- if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maximumSpeed) {
- float fallSpeed = rb.velocity.y;
- Vector3 n = rb.velocity.normalized * maximumSpeed;
- rb.velocity = new Vector3(n.x, fallSpeed, n.z);
- }
- }
- void AddCounterForce(Vector3 direction,float axis,float magnitude){
- if (Math.Abs(magnitude) > threshold && Math.Abs(axis) < 0.05f || (magnitude < -threshold && axis > 0) || (magnitude > threshold && axis < 0))
- rb.AddForce(defaultMovementSpeed * direction * Time.deltaTime * -magnitude * counterMovement);
- }
- public Vector2 GetCurrentVelocity() {
- float lookAngle = orientation.transform.eulerAngles.y;
- float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
- float u = Mathf.DeltaAngle(lookAngle, moveAngle);
- return new Vector2( rb.velocity.magnitude * Mathf.Cos((90 - u) * Mathf.Deg2Rad),rb.velocity.magnitude * Mathf.Cos(u * Mathf.Deg2Rad));
- }
- private bool IsOnFloor(Vector3 v) {
- float angle = Vector3.Angle(Vector3.up, v);
- return angle < maxSlopeAngle;
- }
- private void OnCollisionStay(Collision other) {
- int layer = other.gameObject.layer;
- if (whatIsGround != (whatIsGround | (1 << layer))) return;
- for (int i = 0; i < other.contactCount; i++) {
- Vector3 FloorContact = other.contacts[i].normal;
- if (IsOnFloor(FloorContact)) {
- isGrounded = true;
- cancellingGrounded = false;
- defaultVector = FloorContact;
- CancelInvoke(nameof(StopGrounded));
- }
- }
- float delay = 3f;
- if (!cancellingGrounded) {
- cancellingGrounded = true;
- Invoke(nameof(StopGrounded), Time.deltaTime * delay);
- }
- }
- private void StopGrounded() {
- isGrounded = false;
- }
- }
- __________________________________________________________________________________
- public class PlayerRaycast :NetworkBehaviour
- {
- RaycastHit hit;
- GameObject prevObject;
- EventObject prevEventObject;
- public Camera mainCamera;
- EventObject eventObject;
- void Input(){
- if(Input.GetKeyDown(KeyCode.E))
- {
- Click();
- }
- if(Input.GetKeyUp(KeyCode.E))
- {
- DeClick();
- }
- }
- void Update()
- {
- if(!isLocalPlayer)
- return;
- if (IsLookingAtRaycastableObject()&&!IsPlayerCurrentlyHolding()){
- eventObject=hit.collider.transform.gameObject.GetComponent<EventObject>();
- HighLightCurrentObject();
- TogglePlayerPickUp(false);
- Input();
- }
- if(StoppedLookingAtPreviousObject()){
- DeHighLightPreviousObject();
- TogglePlayerPickUp(true);
- prevObject=null;
- }
- StoreCurrentObject();
- }
- public void Click(){
- eventObject.Click(this.GetComponent<PlayerAuth>());
- }
- public void DeClick(){
- eventObject.DeClick();
- }
- public void HighLightCurrentObject(){
- eventObject.HighLight(true);
- }
- public void DeHighLightPreviousObject(){
- prevEventObject.HighLight(false);
- }
- public void StoreCurrentObject(){
- if(hit.normal!=Vector3.zero)// if we encountered an object before, store it so we can dehighlight it after leaving it
- {
- prevObject=hit.collider.gameObject;
- prevEventObject=eventObject;
- }
- }
- public bool StoppedLookingAtPreviousObject(){
- return (prevObject!=null&&hit.collider!=null&&prevEventObject!=null&&prevObject!=hit.collider.gameObject);
- }
- public bool IsLookingAtRaycastableObject(){
- return Physics.Raycast(mainCamera.transform.position,mainCamera.transform.forward, out hit, 100.0f)&&hit.collider.transform.tag=="Raycastable";
- }
- public bool IsPlayerCurrentlyHolding(){
- return this.GetComponent<RbPickUp>().IsCurrentlyHolding();
- }
- public void TogglePlayerPickUp(bool flag){
- this.GetComponent<RbPickUp>().TogglePickupFeature(flag);
- }
- }
- _______________________________---
- public class ObjectAuthority : NetworkBehaviour
- {
- PlayerAuth currentPlayerWithAuth;
- public void GiveAuth(PlayerAuth player){
- if(!hasAuthority&¤tPlayerWithAuth!=null){
- RemoveAuth();
- }
- player.GiveAuthority(this.GetComponent<NetworkIdentity>());
- currentPlayerWithAuth=player;
- }
- public void RemoveAuth(){
- currentPlayerWithAuth.RemoveAuthority(this.GetComponent<NetworkIdentity>());
- }
- }
- ____________________--
- public class EventObject: MonoBehaviour
- {
- public UnityEvent onClickEvent;
- public UnityEvent deClickEvent;
- public AuthorityEvent takeAuthEvent;
- public UnityEvent onHighlightEvent;
- public UnityEvent onDeHighlightEvent;
- void Awake(){
- if(onClickEvent==null){
- onClickEvent=new UnityEvent();
- }
- if(onHighlightEvent==null){
- onHighlightEvent=new UnityEvent();
- }
- if(onDeHighlightEvent==null){
- onDeHighlightEvent=new UnityEvent();
- }
- }
- public void Click(PlayerAuth playerAuth){
- takeAuthEvent.Invoke(playerAuth);
- onClickEvent.Invoke();
- }
- public void DeClick(){
- deClickEvent.Invoke();
- }
- public void HighLight(bool isHighlighted){
- if(isHighlighted){
- onHighlightEvent.Invoke();
- }
- else{
- onDeHighlightEvent.Invoke();
- }
- }
- __________________________________________--
- public class RbPickUp : NetworkBehaviour
- {
- public string pickableObjectsTag;
- public GameObject pickedObjectGuide;
- public PickUpTrigger pickUpTrigger;
- public Camera playerCamera;
- [Range(100, 5000)]
- public float throwForce = 1000;
- [Range(0.01f, 1)]
- public float centerizationSpeed = 0.01f;
- GameObject objectBeingPicked;
- Rigidbody objectBeingPickedRigidBody;
- Rigidbody characterController;
- bool isBeingHeld = false;
- bool canPickup = true;
- private void Start()
- {
- characterController = this.GetComponent<Rigidbody>();
- }
- public bool canBePickedUp()
- {
- return (!isBeingHeld && pickUpTrigger.highLightedObject != null&&pickUpTrigger.highLightedObject.CompareTag(pickableObjectsTag));
- }
- void checkInput()
- {
- if (Input.GetKeyDown(KeyCode.E) && canBePickedUp())
- {
- PickUpObject();
- }
- else if (Input.GetKeyDown(KeyCode.E) && isBeingHeld)
- {
- PutDownObject();
- }
- else if (Input.GetMouseButton(1) && isBeingHeld)
- {
- ThrowObject();
- }
- }
- void Update()
- {
- if (canPickup)
- {
- if (objectBeingPicked == null || objectBeingPicked.Equals(null)) //this handles if the object got destroyed while its being held
- isBeingHeld = false;
- checkInput();
- if (isBeingHeld)
- {
- ParentObject();
- }
- }
- }
- void ParentObject()
- {
- objectBeingPicked.transform.position = pickedObjectGuide.transform.position;
- objectBeingPicked.transform.rotation = pickedObjectGuide.transform.rotation;
- }
- #region PickUP
- void PickUpObject(){
- objectBeingPicked = pickUpTrigger.highLightedObject;
- isBeingHeld = true;
- CmdPickUpObject(objectBeingPicked);
- objectBeingPickedRigidBody = objectBeingPicked.GetComponent<Rigidbody>();
- objectBeingPickedRigidBody.Sleep();
- objectBeingPickedRigidBody.useGravity = false;
- }
- [Command]
- void CmdPickUpObject(GameObject objectBeingPicked)
- {
- objectBeingPicked.GetComponent<NetworkIdentity>().AssignClientAuthority(this.GetComponent<NetworkIdentity>().connectionToClient);
- isBeingHeld = true;
- objectBeingPickedRigidBody = objectBeingPicked.GetComponent<Rigidbody>();
- objectBeingPickedRigidBody.Sleep();
- objectBeingPickedRigidBody.useGravity = false;
- }
- #endregion
- #region PutDown
- public void putDownOnTriggerExit(Collider col)
- {
- if (col.gameObject == objectBeingPicked)
- {
- PutDownObject();
- }
- }
- void PutDownObject()
- {
- isBeingHeld = false;
- objectBeingPickedRigidBody.AddForce(characterController.velocity, ForceMode.VelocityChange); //add player's velocity
- objectBeingPickedRigidBody.WakeUp();
- objectBeingPickedRigidBody.useGravity = true;
- CmdPutDownObject(objectBeingPicked);
- objectBeingPicked = null;
- objectBeingPickedRigidBody = null;
- }
- [Command]
- void CmdPutDownObject(GameObject objectBeingPicked)
- {
- isBeingHeld = false;
- Rigidbody objectBeingPickedRigidBody=objectBeingPicked.GetComponent<Rigidbody>();
- objectBeingPickedRigidBody.AddForce(characterController.velocity, ForceMode.VelocityChange);
- objectBeingPicked.transform.SetParent(null);
- objectBeingPickedRigidBody.WakeUp();
- objectBeingPickedRigidBody.useGravity = true;
- objectBeingPicked.GetComponent<NetworkIdentity>().RemoveClientAuthority();
- objectBeingPicked = null;
- objectBeingPickedRigidBody = null;
- }
- #endregion
- #region Throw
- void ThrowObject()
- {
- Vector3 throwDirection = playerCamera.transform.forward * throwForce; //camera's direction
- Vector3 playersVelocity = characterController.velocity; //camera's direction
- objectBeingPickedRigidBody.AddForce(throwDirection, ForceMode.Force); //add player's velocity
- objectBeingPickedRigidBody.AddForce(playersVelocity, ForceMode.VelocityChange); //add player's velocity
- CmdThrowObject();
- PutDownObject();
- }
- [Command]
- void CmdThrowObject()
- {
- Vector3 throwDirection = playerCamera.transform.forward * throwForce; //camera's direction
- Vector3 playersVelocity = characterController.velocity; //camera's direction
- objectBeingPickedRigidBody.AddForce(throwDirection, ForceMode.Force); //add player's velocity
- objectBeingPickedRigidBody.AddForce(playersVelocity, ForceMode.VelocityChange); //add player's velocity
- PutDownObject();
- }
- #endregion
- public void TogglePickupFeature(bool canMove)//todo make a better name
- {
- this.canPickup = canMove;
- }
- public bool IsCurrentlyHolding(){
- return this.isBeingHeld;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement