public GameObject Miffy;
void OnTriggerEnter(Collider collider)
{
//when space key is pressed and collider is miffy(tagged Player)
if (Input.GetKey(KeyCode.P) && collider.gameObject.tag == "Player")
{
Ball.transform.parent = Miffy.transform;
Ball.transform.localPosition = new Vector3(0, 0, 0);
}
}
private void Update()
{
//when key D is pressed miffy is no longer parent to ball object.
if (Input.GetKeyDown(KeyCode.D))
{
Ball.transform.SetParent(null);
}
}
child object (Ball) increasing distance as parent(Miffy) object moves about.
It seems that Ball
is a Rigidbody
.
You should not nest multiple Rigidbody
or move a parent of a Rigidbody
at all.
Rather use a FixedJoint
.
Afaik you can simply do something like
private Rigidbody miffyRigidbody;
private FixedJoint BallFixedJoint;
void OnTriggerEnter(Collider collider)
{
isColliding = true;
if (collider.CompareTag("Player"))
{
miffyRigidbody = collider.attachedRigidbody;
}
}
void OnTriggerExit(Collider collider)
{
if (collider.CompareTag("Player"))
{
miffyRigidbody = null;
}
}
private void Update()
{
if(miffyRigidbody && Input.GetKeyDown(KeyCode.P))
{
if(!BallFixedJoint)
{
BallFixedJoint = Ball.GetComponent<FixedJoint>();
if(!BallFixedJoint) BallFixedJoint = Ball.AddComponent<FixedJoint>();
}
BallFixedJoint.connectedBody = Miffy.GetComponent<Rigidbody>();
}
if(Input.GetKeyUp(KeyCode.P))
{
if(!BallFixedJoint)
{
BallFixedJoint = Ball.GetComponent<FixedJoint>();
if(!BallFixedJoint) BallFixedJoint = Ball.AddComponent<FixedJoint>();
}
BallFixedJoint.connectedBody = null;
}
}