Advertisement
Rugbug_Redfern

GravityGun.cs

Jul 17th, 2020
5,598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GravityGun : MonoBehaviour
  6. {
  7.  
  8.     [SerializeField] Camera cam;
  9.     [SerializeField] float maxGrabDistance = 10f, throwForce = 20f, lerpSpeed = 10f;
  10.     [SerializeField] Transform objectHolder;
  11.  
  12.     Rigidbody grabbedRB;
  13.  
  14.     void Update()
  15.     {
  16.         if(grabbedRB)
  17.         {
  18.             grabbedRB.MovePosition(Vector3.Lerp(grabbedRB.position, objectHolder.transform.position, Time.deltaTime * lerpSpeed));
  19.  
  20.             if(Input.GetMouseButtonDown(0))
  21.             {
  22.                 grabbedRB.isKinematic = false;
  23.                 grabbedRB.AddForce(cam.transform.forward * throwForce, ForceMode.VelocityChange);
  24.                 grabbedRB = null;
  25.             }
  26.         }
  27.  
  28.         if(Input.GetKeyDown(KeyCode.E))
  29.         {
  30.             if(grabbedRB)
  31.             {
  32.                 grabbedRB.isKinematic = false;
  33.                 grabbedRB = null;
  34.             }
  35.             else
  36.             {
  37.                 RaycastHit hit;
  38.                 Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
  39.                 if(Physics.Raycast(ray, out hit, maxGrabDistance))
  40.                 {
  41.                     grabbedRB = hit.collider.gameObject.GetComponent<Rigidbody>();
  42.                     if(grabbedRB)
  43.                     {
  44.                         grabbedRB.isKinematic = true;
  45.                     }
  46.                 }
  47.             }
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement