- Home /
Maintain velocity after impact with kinematic rigidbody
So right now this seems to be working for me but I wanted to check to see if it's the best way to do this. I want to hit a kinematic rigidbody that tests the collisions to see if the relativeVelocity.magnitude reaches a high enough level to break the object and spawn pieces. If the check passes I want the collider to maintain its velocity after the collision with the kinematic rigidbody...so I'm doing that by directly changing the collider.velocity to the collision.relativeVelocity. Seems to work in my limited testing but I wanted to make sure there's not a better way to do this.
Thanks in advance :)
var ShaperBlockPrefab : Transform;
function OnCollisionEnter(collision : Collision) {
if (collision.relativeVelocity.magnitude > 100){
var spawnPoint : Vector3 = Vector3(transform.position.x, transform.position.y -18, transform.position.z);
Instantiate (ShaperBlockPrefab, spawnPoint, transform.rotation);
collision.collider.rigidbody.velocity = collision.relativeVelocity;
Destroy(gameObject);
}
}
Answer by Owen-Reynolds · May 23, 2011 at 10:42 PM
Relative velocity is your speed minus their speed, so only works if the "smashees" aren't moving (if one was moving towards you, the relative velocity is higher, so you speed up after the hit.)
My current untested solution is to save oldVelocity
each frame(in fixedUpdate) and restore it after the crash, as needed. Either that or petition UnityDev to make a "OnPreCollisionEnter()" which is called just before physics is applied, with a "skipPhysics" optional flag.
Thanks I'll give that a try. The "speed up" with my current setup doesn't appear to be visually distinguishable so I may be able to still run with it. I appreciate the help :)
In this case the smashee is$$anonymous$$inematic, so not an issue.
A "realistic" effect would require subtracting a fixed amount of energy (the energy required to smash) from the current energy of the smasher, and also conserve momentum by imparting velocity to the smash particles.
It's a long time since I did Physics, but I have an intuitive feeling that you can calculate all that with what Unity provides already, since rigidbody physics does not require a fixed frame of reference. You can effectively "undo" a collision (after destroying one of the colliders) by applying forces negative to those that resulted from the collision, which would seem to be calculable from the collision normal, body masses, post-collision velocities, and relative velocities at collision.
But I could be drea$$anonymous$$g.