I made a script that allows the player to pick up and move a cube. When the player hits the cube with a raycast, it adds a fixed joint, resets the position, bla bla bla…
My problem is that if the player is holding the cube and they press it against a wall or on any sort of collider, the cube starts to spaz out and glitch. I tried to solve this by adding a break force to the joint, but now when the joint “breaks” my cube is still floating around without gravity and is still parented to my player. How can I make the cube drop when the joint is broken? Or at least not glitch out when it is being pushed against a collider?
Heres the code for picking it up and dropping it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UseManager : MonoBehaviour
{
public GameObject cube;
RaycastHit hit;
public GameObject cubeHolder;
public Transform cubeHolderTransform;
public FixedJoint joint;
public bool isHolding = false;
public void dropCube()
{
Destroy(cube.GetComponent<FixedJoint>());
cube.transform.parent = null;
cube.GetComponent<Rigidbody>().useGravity = true;
cube.transform.localRotation = transform.rotation;
isHolding = false;
StartCoroutine(wait1());
Debug.Log("Cube dropped");
}
IEnumerator wait1()
{
yield return new WaitForSeconds(0.5f);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (Physics.Raycast(transform.position, transform.forward, out hit, 2.5f))
{
//Cube pickup script
if ((hit.transform.tag == "cube") && isHolding == false)
{
cube = hit.transform.gameObject;
cube.transform.position = cubeHolder.transform.position;
cube.transform.localRotation = transform.rotation;
cube.transform.SetParent(cubeHolderTransform);
cube.GetComponent<Rigidbody>().useGravity = false;
joint = cube.gameObject.AddComponent<FixedJoint>();
joint.connectedBody = cubeHolder.GetComponent<Rigidbody>();
isHolding = true;
StartCoroutine(wait1());
}
else if (isHolding == true)
{
dropCube();
}
}
}
}
}