Hello everyone!
I have some trouble with this situation:
Let’s suppose I have a long pillar on the ground, then it’s hitted by a cannon ball, and so it falls. I would need to get the impulse collision when it hits the ground.
I cannot use OnCollisionEnter, because the pillar was hitting the ground from the start.
So, I was trying to recreate the code of collision.impulse. In order to be sure I don’t make any mistakes, I tried to test it during an actual collision, but It seems my actual code is incorrect
private void OnCollisionEnter(Collision collision)
{
Rigidbody CollisionBody = collision.rigidbody;
if (CollisionBody != null)
{
Vector3 MyPreviousVelocity = MyPreviousVelocityTracker.PreviousVelocity;
Vector3 CollisionPreviousVelocity = collision.gameObject.GetComponent<PreviousVelocityTracker>().PreviousVelocity;
Debug.Log("impulse: " + collision.impulse);
Debug.Log("Maybe impulse: " + ((MyBody.mass * (MyBody.velocity - MyPreviousVelocity)
+ (CollisionBody.velocity - CollisionPreviousVelocity) * CollisionBody.mass)));
Debug.Log("My DiffMomentum: " + (MyBody.mass * (MyBody.velocity - MyPreviousVelocity)));
Debug.Log("ItsDiffMomentum: " + (CollisionBody.velocity - CollisionPreviousVelocity) * CollisionBody.mass);
}
}
where
public class PreviousVelocityTracker : MonoBehaviour
{
[HideInInspector]
public Vector3 PreviousVelocity;
[HideInInspector]
public bool StopTracking;
private Rigidbody MyBody;
private void Awake()
{
MyBody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (!StopTracking) PreviousVelocity = MyBody.velocity;
}
}
if collision.impulse is “the total impulse applied to this contact pair to resolve the collision” I thought I could get it by the sum of the difference of the momentum of the two objects in two consecutive fixedframes, but the result I get is very different:
Output example:
impulse: (-4.1, 0.0, 0.0)
Maybe impulse: (-1.9, 0.3, -1.4)
My DiffMomentum: (2.2, 0.3, 0.4)
ItsDiffMomentum: (-4.1, 0.0, -1.8)
I noticed that most of time the impulse is very similar to “ItsDiffMomentum”, sometimes is similar to “My DiffMomentum”, rarely is completely different from both and almost never is similar to “Maybe impulse”.
Can anyone help me?
Thank you a lot! ^^