How can I properly make a GameObject attach (or "stick") to another GameObject after collision? The problem: I want the GameObject to attach after collision even if it is changing scale.
"Attach on collision" code:
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;
}
This code makes a GameObject attach perfectly after collision. But when that GameObject changes scale (while it's attached), it visually no longer looks attached to whatever it collided with. Basically, this code makes the GameObject stick with only the original scale at the moment of the collision. How can I make the GameObject always stick to whatever it collided with? And with whatever scale it has during the process? I would like to avoid parenting: "It's a bit unsafe though, parenting colliders can cause weird results, like random teleporting or object starting to move and rotate insanely, etc." - Samed Tarık ÇETİN : comment.
Scaling script:
public Transform object1; //this is the object that my future-scaling GameObject collided with.
public Transform object2; //another object, the same scale as object1, somewhere else
//(or vice versa)
void Update ()
{
float distance = Vector3.Distance (object1.position, object2.position);
float original_width = 10;
if (distance <= 10)
{
float scale_x = distance / original_width;
scale_x = Mathf.Min (scale_x, 3.0f);
transform.localScale = new Vector3 (scale_x * 3.0f, 3.0f / scale_x, 3.0f);
}
}