using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpController : MonoBehaviour
{
public ProjectileGun gunScript;
public Grappling grapplingScript;
public Rigidbody rb;
public BoxCollider coll;
public Transform player, gunContainer, fpsCam;
public float pickUpRange;
public float dropForwardForce, dropUpwardForce;
public bool equipped;
public static bool slotFull;
public bool grappleGun;
private void Start()
{
// Setup
if (!equipped)
{
gunScript.enabled = false;
if (grappleGun) grapplingScript.enabled = false;
rb.isKinematic = false;
coll.isTrigger = false;
}
if (equipped)
{
gunScript.enabled = true;
if (grappleGun) grapplingScript.enabled = true;
rb.isKinematic = true;
coll.isTrigger = true;
slotFull = true;
}
}
private void Update()
{
// Check if player is in range and "E" is pressed
Vector3 distanceToPlayer = player.position - transform.position;
if (!equipped && distanceToPlayer.magnitude <= pickUpRange && Input.GetKeyDown(KeyCode.E) && !slotFull)
{
PickUp();
}
// Drop if equipped and "Q" is pressed
if (equipped && Input.GetKeyDown(KeyCode.Q))
{
Drop();
}
}
private void PickUp()
{
equipped = true;
slotFull = true;
// Make weapon a child of the camera and move it to default position
transform.SetParent(gunContainer);
// use these if the orignal model is perfect shape default
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.Euler(0, 180, 0);
// For the local scale dont use unless the actual model size in project is exactly 1
//transform.localScale = Vector3.zero;
// Make Rigidbody Kinematic and BoxCollider a trigger s
rb.isKinematic = true;
coll.isTrigger = true;
// Enable script
gunScript.enabled = true;
if (grappleGun) grapplingScript.enabled = true;
}
private void Drop()
{
equipped = false;
slotFull = false;
// Set parent to null
transform.SetParent(null);
// Make Rigidbody Kinematic and BoxCollider normal
rb.isKinematic = false;
coll.isTrigger = false;
// Gun carries momentum of player
rb.velocity = player.GetComponent<Rigidbody>().velocity;
// AddForce
rb.AddForce(fpsCam.forward * dropForwardForce, ForceMode.Impulse);
rb.AddForce(fpsCam.up * dropUpwardForce, ForceMode.Impulse);
// Add random rotation
float random = Random.Range(-1f, 1f);
rb.AddTorque(new Vector3(random, random, random) * 10);
// Disable script
gunScript.enabled = false;
if (grappleGun) grapplingScript.enabled = false;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter