Question by
Artonn · Jan 19, 2016 at 07:24 PM ·
playeritem pickupactions
Unity5 Script to pick up a object, and drop it does not work correctly. [Newbie]
So i'm currently trying to make a script that can pick up an object and hold it, while walking around and also drop it whenever it's wanted. I followed this Tutorial, but for some reason it does not want to work correctly.
The item stays on the ground, even when it tells me the item has been picked up.
using UnityEngine;
using System.Collections;
public class PickUpObject : MonoBehaviour
{
public GameObject mainCamera;
bool carrying = false;
public GameObject carriedObject;
public float distance;
public float smooth;
// Use this for initialization
void Start()
{
mainCamera = GameObject.FindWithTag("MainCamera");
}
// Update is called once per frame
void Update()
{
if (carrying)
{
carry(carriedObject);
checkDrop();
//rotateObject();
}
else {
//Debug.Log("can pickup");
pickup();
}
}
void rotateObject()
{
carriedObject.transform.Rotate(5, 10, 15);
}
void carry(GameObject o)
{
Debug.Log("trying to pickup");
o.transform.position = Vector3.Lerp(o.transform.position, mainCamera.transform.position + mainCamera.transform.forward * distance, Time.deltaTime * smooth);
}
void pickup()
{
if (Input.GetKeyDown(KeyCode.E))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y)); // mainCamera.camera.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;
p.gameObject.GetComponent<Rigidbody>().isKinematic = false;
// p.gameObject.GetComponent<Rigidbody>().useGravity = false; // rigidbody.useGravity = false;
}
}
}
}
void checkDrop()
{
if (Input.GetKeyDown(KeyCode.E))
{
dropObject();
}
}
void dropObject()
{
carrying = false;
carriedObject.gameObject.GetComponent<Rigidbody>().isKinematic = false;
//carriedObject.gameObject.GetComponent<Rigidbody>().useGravity = true;
carriedObject = null;
}
}
Also if possible, I would like to be able to rotate the item while holding it or even trow it. But i've got no idea how to do that. :(
Comment