Reputation:
Currently, I am using the following code to make objects stick to other gameObjects:
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
gameObject.transform.SetParent (col.gameObject.transform);
}
It works perfectly, but it causes many other problems. For example, after colliding, it can no longer detect collisions.
Does someone possess an alternative to this code (which makes a gameObject stick to another one after collision)?
Upvotes: 0
Views: 1884
Reputation: 8163
Here's a start for you, please note that this does not take into account rotation, that i'm sure you will be able to figure out, right? ;)
protected Transform stuckTo = null;
protected Vector3 offset = Vector3.zero;
public void LateUpdate()
{
if (stuckTo != null)
transform.position = stuckTo.position - offset;
}
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
if(stuckTo == null
|| stuckTo != col.gameObject.transform)
offset = col.gameObject.transform.position - transform.position;
stuckTo = col.gameObject.transform;
}
EDIT: As promised, here is a more advanced version taking rotation into account:
Transform stuckTo;
Quaternion offset;
Quaternion look;
float distance;
public void LateUpdate()
{
if (stuckTo != null)
{
Vector3 dir = offset * stuckTo.forward;
transform.position = stuckTo.position - (dir * distance);
transform.rotation = stuckTo.rotation * look;
}
}
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
if(stuckTo == null
|| stuckTo != col.gameObject.transform)
{
Vector3 diff = col.gameObject.transform.position - transform.position;
offset = Quaternion.FromToRotation (col.gameObject.transform.forward, diff.normalized);
look = Quaternion.FromToRotation (col.gameObject.transform.forward, transform.forward);
distance = diff.magnitude;
stuckTo = col.gameObject.transform;
}
}
Upvotes: 0