Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Events;
- using UnityEngine.UI;
- public class ChainHandle : MonoBehaviour
- {
- [SerializeField]
- Transform player;
- [SerializeField]
- Transform firstChain;
- float distance;
- bool grabbed;
- BoxCollider col;
- Rigidbody rb;
- [SerializeField]
- Text textPrompt;
- bool inRange;
- // Start is called before the first frame update
- void Start()
- {
- distance = Vector3.Distance(transform.position, firstChain.position);
- PlayerClamped.distance = distance;
- col = GetComponent<BoxCollider>();
- rb = GetComponent<Rigidbody>();
- rb.isKinematic = false;
- rb.useGravity = true;
- }
- void OnDrawGizmos()
- {
- Gizmos.color = Color.yellow;
- if (firstChain != null)
- {
- Gizmos.DrawWireSphere(firstChain.position, distance) ;
- }
- }
- private void Update()
- {
- if (Input.GetKeyDown(KeyCode.E))
- {
- Grab();
- }
- }
- private void FixedUpdate()
- {
- if (grabbed)
- {
- // towards "player"
- Vector3 dir = player.transform.position - firstChain.transform.position;
- // clamp length
- dir = Vector3.ClampMagnitude(dir, distance);
- // add clamped length
- transform.position = firstChain.transform.position + dir;
- // look towards movement
- transform.rotation = Quaternion.LookRotation(-dir);
- }
- }
- void Grab()
- {
- grabbed = !grabbed;
- col.enabled = !grabbed;
- rb.isKinematic = grabbed;
- rb.useGravity = !grabbed;
- textPrompt.text = "Press E to drop";
- }
- private void OnTriggerEnter(Collider other)
- {
- if(other.gameObject == player.gameObject)
- {
- inRange = true;
- other.GetComponent<PlayerClamped>().inRange = true;
- textPrompt.text = "Press E to grab";
- }
- }
- private void OnTriggerExit(Collider other)
- {
- if (other.gameObject == player.gameObject)
- {
- inRange = true;
- other.GetComponent<PlayerClamped>().inRange = false;
- textPrompt.text = "";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment