- Home /
Saving player momentum after collision with object, that is destroyed after collision
I want to implement a mechanic, when a player collides with an object with decent momentum, the object should be "deconstructed" (parts of the object deattach from original object with its own rigidbody (e.x. wheels from a car)), this way creating some sort of destructable environment.
Problem is when player collides with an object at some speed, he loses that speed, as if the object was kinematic (it is kinematic from the beginning, but when player collides with it, an object should "deconstruct") and only after losing speed object "deconstructs".
How can I make an object "deconstruct" on collision without losing much of player's speed?
P.S. Player movement is in Update.
P.S.S. I can freeze position and rotation of an object and remove kinematic option, and it works, but then I get weird physics behaviour when non-player object (tank in my case) drives onto freezed object.
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
hp -= collision.transform.GetComponent<Rigidbody>().velocity.magnitude * collision.transform.GetComponent<Rigidbody>().mass;
if (hp <= 0)
{
transform.GetComponent<Rigidbody>().isKinematic = false;
Deconstruct();
}
}
}
public void Deconstruct()
{
Transform[] allChildren = GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
child.gameObject.AddComponent<Rigidbody>();
child.GetComponent<Rigidbody>().useGravity = true;
child.parent = null;
}
}
Your answer
