Question by
jparell · Aug 02, 2020 at 04:26 PM ·
c#programming
pickup object is floating in the air when dropped.
I have a pickup script, when the player is next to an object the player presses E to pickup the object and carry it around in front of them, when I drop the object it doesn't drop to the ground like gravity doesn't work. I already have a rigidbody attached to the object with gravity checked and kinematic checked when I unchecked kinematic, the object drops to the ground like I would like it to but then I can't even pick it up. How can I fix my code so that the object uses gravity and I can pick it up?
Here is my code that I have for the pickup object...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpAble : MonoBehaviour
{
GameObject mainCamera;
GameObject carriedObject;
bool carrying;
public float distance;
public float smooth;
public float rayDistance;
float startYRotation;
float deltaRotation;
float yRotation;
float previousUp;
Quaternion offset;
void Start()
{
mainCamera = GameObject.FindWithTag("MainCamera");
}
void Update()
{
if (carrying)
{
carry(carriedObject);
checkDrop();
}
else
{
pickup();
}
}
void carry(GameObject o)
{
o.transform.position = Vector3.Lerp(o.transform.position, mainCamera.transform.position + mainCamera.transform.forward * distance, Time.deltaTime * smooth);
deltaRotation = previousUp - mainCamera.transform.eulerAngles.y;
yRotation = startYRotation - deltaRotation;
Quaternion target = Quaternion.Euler(0, yRotation, 0);
o.transform.rotation = Quaternion.Slerp(o.transform.rotation, target, Time.deltaTime * 3);
}
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));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayDistance))
{
PickUpAble p = hit.collider.GetComponent<PickUpAble>();
if (p != null)
{
if (Input.GetKeyDown(KeyCode.E))
{
carrying = true;
carriedObject = p.gameObject;
p.GetComponent<Rigidbody>().useGravity = false;
previousUp = mainCamera.transform.eulerAngles.y;
startYRotation = carriedObject.transform.eulerAngles.y;
}
}
}
}
}
void checkDrop()
{
if (Input.GetKeyDown(KeyCode.E))
{
carrying = false;
GetComponent<Rigidbody>().useGravity = true;
dropObject();
}
}
void dropObject()
{
carrying = false;
carriedObject.GetComponent<Rigidbody>().useGravity = true;
carriedObject = null;
}
}`enter code here`
Comment