Advertisement
GoodNoodle

GrabObjects

Nov 5th, 2023
642
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.66 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GrabObjects : MonoBehaviour
  6. {
  7.     public Transform holdSpot;
  8.     public LayerMask pickUpMask;
  9.  
  10.     public Vector3 direction { get;  set; }
  11.  
  12.     public GameObject itemToHold;
  13.  
  14.     public bool isgrabbed;
  15.  
  16.     // Update is called once per frame
  17.     void Update()
  18.     {
  19.         if (Input.GetKeyDown(KeyCode.Space) && isgrabbed == false)
  20.         {
  21.             GrabObject();
  22.         }          
  23.     }
  24.  
  25.     void GrabObject()
  26.     {
  27.                 if(itemToHold)
  28.             {
  29.                 itemToHold.transform.position = transform.position + direction;
  30.                 itemToHold.transform.parent = null;
  31.  
  32.                 if (itemToHold.GetComponent<Rigidbody2D>())
  33.                 {
  34.                     itemToHold.GetComponent<Rigidbody2D>().simulated = true;
  35.                 }
  36.  
  37.             } else
  38.  
  39.             {
  40.     Collider2D pickupItem = Physics2D.OverlapCircle(transform.position + direction, .4f, pickUpMask);
  41.             if(pickupItem)
  42.             {
  43.                 //isgrabbed = true;
  44.                 itemToHold = pickupItem.gameObject;
  45.                 itemToHold.transform.position = holdSpot.position;
  46.                 itemToHold.transform.parent = transform;
  47.                
  48.  
  49.  
  50.                 if (itemToHold.GetComponent<Rigidbody2D>())
  51.                 {
  52.                     itemToHold.GetComponent<Rigidbody2D>().simulated = false;
  53.                 }
  54.             } else if (Input.GetKeyDown(KeyCode.Space))
  55.             {
  56.                 itemToHold = null;
  57.                 isgrabbed = false;
  58.             }
  59.  
  60.             }
  61.      
  62.  
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement