I am creating a 3rd person puzzle game and I am able to have the character pickup and drop an object that has this script with the ‘K’ key. The problem is, I can’t figure out how to have the object be picked up only when the character gets within a certain range. If I don’t do this, any object with this scrip will teleport to the front of the character from any place on the game.
So how do I allow objects that can be picked up only be picked up when the character is close to them?
Here is the script that allows the object to be picked up and dropped using the ‘K’ key.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pickable : MonoBehaviour
{
public GameObject item;
public GameObject tempParent;
public Transform guide;
bool carrying;
// Use this for initialization
void Start()
{
item.GetComponent<Rigidbody>().useGravity = true;
}
// Update is called once per frame
void Update()
{
if (carrying == false)
{
if (Input.GetKeyDown(KeyCode.K))
{
pickup();
carrying = true;
}
}
else if (carrying == true)
{
if (Input.GetKeyDown(KeyCode.K))
{
drop();
carrying = false;
}
}
}
void pickup()
{
item.GetComponent<Rigidbody>().useGravity = false;
item.GetComponent<Rigidbody>().isKinematic = true;
item.transform.position = guide.transform.position;
item.transform.rotation = guide.transform.rotation;
item.transform.parent = tempParent.transform;
}
void drop()
{
item.GetComponent<Rigidbody>().useGravity = true;
item.GetComponent<Rigidbody>().isKinematic = false;
item.transform.parent = null;
item.transform.position = guide.transform.position;
}
}