I'm trying to work with picking up and throwing objects. So far I've come up with a solution which does pick up the object but the same time disappears the object also. Please check to the functionality I've used.
public class pickupobject : MonoBehaviour {
//GameObject mainCamera;
bool carrying;
GameObject carriedObject;
Camera cam;
public float distances;
public float smooth;
// Use this for initialization
void Start()
{
cam = GameObject.Find("MainCamera").GetComponent<Camera>();
}
// Update is called once per frame
void Update () {
if(carrying)
{
carry(carriedObject);
}
else
{
pickup();
}
}
private void pickup()
{
if(Input.GetKeyDown(KeyCode.E))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = cam.ScreenPointToRay(new Vector3(x, y));
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
pickupable p = hit.collider.GetComponent<pickupable>();
if(p!=null)
{
carrying = true;
carriedObject = p.gameObject;
}
}
}
}
void carry(GameObject o)
{
o.GetComponent<Rigidbody>().isKinematic = true;
o.transform.position = o.transform.position + cam.transform.position + cam.transform.forward * distances;
}
}