- Home /
How to stop the carried object from moving way when parented to the player camera?
Hey guys, I have been doing some research into this problem I am having. I have created a pick up and carry script. When the player picks up the object, the carried object parents to the camera. The problem is when I walk forward or the carried object hits another collider, the object starts rotating and moving away randomly. how can I stop this from happening? Thanks in advance
public class HoldItem : MonoBehaviour
{
public GameObject playerCamera;
public GameObject carriedItem;
private RaycastHit hit;
public bool hasItem = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Physics.Raycast(transform.position, transform.forward, out hit, 100))
{
if (hit.collider.gameObject.tag == "Fuel Tank")
{
carriedItem = hit.collider.gameObject;
}
else if(!hasItem)
{
carriedItem = null;
}
}
if (Input.GetKeyDown(KeyCode.E) && !hasItem && carriedItem != null)
{
PickUpItem();
hasItem = true;
}
if (Input.GetKeyDown(KeyCode.D) && hasItem && carriedItem != null)
{
DropItem();
hasItem = false;
}
}
void PickUpItem()
{
carriedItem.transform.parent = playerCamera.transform;
carriedItem.GetComponent<Rigidbody>().useGravity = false;
}
void DropItem()
{
carriedItem.transform.parent = null;
carriedItem.GetComponent<Rigidbody>().useGravity = true;
}
}
Answer by ImpOfThePerverse · Oct 04, 2017 at 03:25 AM
I think having a rigidbody on the carried item is causing the problem, but it's necessary and I don't think you can temporarily disable it, but you could try attaching the carried item via a fixed joint instead of parenting.
Thanks for the answer, never heard of fixed joints. So how would do it ins$$anonymous$$d parenting ?
Answer by Cuttlas-U · Oct 04, 2017 at 03:34 AM
hi; the problem is because of the RigidBody Component + Collider that these components together are doing physics to your object;
so u can disable Collider for a while its your carried object and enable it again when u need :
carriedObject.GetComponent<Collider>().enabled = false;
or u can turn RigidBody to IsKinematic for a while so it wont simulate any phisycs :
carriedObject.GetComponent<RigidBody>().IsKinematic = true;
Good Luck
But that means that the carried object will go through the terrain and walls
well u said it has been carrying by the player so if player dont go inside the terrain the carried object wont go eaither;
Nah, I see what you mean, but I meant to say that it is parent to the player camera so you can move the object around where you look, but when the object hits another object it flies off
aha so u can freez the object rotaition ;
u wont get better result with joints , it has its own problems;
but in the Rigid Body compoentn just lock and free the x y z rotaition and i think u get a better results;