Advertisement
Hyperspace_Wizard

Rimor_Grapple

Jul 5th, 2021
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Grapple : MonoBehaviour
  6. {
  7.     public GrapplingHook grapplingHook;
  8.     [HideInInspector] public Rigidbody2D rb;
  9.     [HideInInspector] public Collider2D collider;
  10.  
  11.     public GameObject attachedTo;
  12.  
  13.     private void Awake()
  14.     {
  15.         rb = GetComponent<Rigidbody2D>();
  16.         collider = GetComponent<Collider2D>();
  17.     }
  18.  
  19.     private void Update()
  20.     {
  21.         if (attachedTo && !attachedTo.activeSelf) grapplingHook.UnGrapple();
  22.     }
  23.  
  24.     private void OnCollisionEnter2D(Collision2D collision)
  25.     {
  26.         if (grapplingHook.isGrappled) return;
  27.  
  28.         // Is the collision grappleable
  29.         if (grapplingHook.whatIsGrappleAble == (grapplingHook.whatIsGrappleAble | (1 << collision.gameObject.layer)))
  30.         {
  31.             // Did we hit a physics object?
  32.             Rigidbody2D collidingBody = collision.gameObject.GetComponent<Rigidbody2D>();
  33.             if (collidingBody != null)
  34.             {
  35.                 transform.SetParent(collidingBody.transform);
  36.                 rb.velocity = Vector2.zero;
  37.                 rb.isKinematic = true;
  38.                 collider.isTrigger = true;
  39.                 grapplingHook.joint.connectedBody = collidingBody;
  40.                 grapplingHook.Grappled();
  41.                 grapplingHook.joint.connectedAnchor = transform.localPosition;
  42.             }
  43.             else
  44.             {
  45.                 rb.velocity = Vector2.zero;
  46.                 rb.isKinematic = true;
  47.                 collider.isTrigger = true;
  48.                 grapplingHook.joint.connectedBody = rb;
  49.                 grapplingHook.Grappled();
  50.                 grapplingHook.joint.connectedAnchor = Vector2.zero;
  51.             }
  52.  
  53.             attachedTo = collision.gameObject;
  54.         }
  55.         else
  56.         {
  57.             // Hit non-grappleable layer, ungrapple
  58.             grapplingHook.UnGrapple();
  59.         }
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement