Guest User

PlayerClamped.cs

a guest
Jun 23rd, 2020
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5.  
  6. public class PlayerClamped : MonoBehaviour
  7. {
  8.  
  9.     private Rigidbody rb;
  10.     private Vector3 moveDirection;
  11.     private float moveSpeed = 4f;
  12.     public static float distance;
  13.  
  14.     [SerializeField]
  15.     Transform firstChain;
  16.     bool grabbed;
  17.     // Use this for initialization
  18.    public bool inRange;
  19.     void Start()
  20.     {
  21.         rb = GetComponent<Rigidbody>();    
  22.     }
  23.     // Update is called once per frame
  24.     void Update()
  25.     {
  26.         if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
  27.         {
  28.             moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
  29.         }
  30.         else
  31.         {
  32.             moveDirection = Vector3.zero;
  33.         }
  34.  
  35.         if (Input.GetKeyDown(KeyCode.E) && inRange)
  36.         {
  37.             Grab();
  38.         }
  39.        
  40.        if (moveDirection != Vector3.zero)
  41.           {
  42.                 transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.15F);
  43.                 moveDirection = new Vector3(moveDirection.x * moveSpeed, Mathf.Clamp(rb.velocity.y, -5, 5), moveDirection.z * moveSpeed);
  44.                 rb.velocity = moveDirection;
  45.  
  46.             if (grabbed)
  47.             {
  48.                 // towards "player"
  49.                 Vector3 dir = transform.position - firstChain.transform.position;
  50.                 // clamp length
  51.                 dir = Vector3.ClampMagnitude(dir, distance);
  52.                 // add clamped length
  53.                 transform.position = firstChain.transform.position + dir;
  54.                 // look towards movement
  55.                 transform.rotation = Quaternion.LookRotation(-dir);
  56.             }
  57.          }
  58.          else
  59.          {
  60.                 rb.velocity = new Vector3(moveDirection.x, Mathf.Clamp(rb.velocity.y, -5, 5), moveDirection.z);
  61.          }
  62.      
  63.     }
  64.  
  65.     void Grab()
  66.     {
  67.         grabbed = !grabbed;
  68.        
  69.          
  70.  
  71.        
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment