Currently, I am using the following code to make objects stick to other gameObjects.
rb = GetComponent();
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... Is there an alternative to this code (which makes a gameObject stick to another one after collision)?
Answer
Instead of parenting it to the other object you can do the following:
- Give it a member variable of type GameObject, initialized to
null
. - When it collides with another object, assign the object it collided with to that variable.
- On every frame, if the variable is not
null
, update the position relative to the other object's position.
This way you also avoid problems you might get when the other object already has child objects you do stuff with in your code.
Edit:
Code Example:
// The class where you make your collision check
public class YourClass : Monobehaviour {
// add this to your class fields
private GameObject collidedObject = null;
void Update()
{
collidedObject = theOtherObject; // do collision check, replace with collided object
if (collidedObject != null)
{
Vector3 offset = new Vector3(0, 0, 1); // replace with your desired offset vector
transform.position = collidedObject.transform.position + offset;
}
// rest of your Update method
}
// rest of your class
}
Be advised that this is not tested code, but it should be enough to illustrate the solution.
No comments:
Post a Comment