- Home /
Need to get physics info on gameObject just before OnCollisionEnter2D
I have a need to know the direction, velocity and other aspects of a rigidbody just before it's acted upon by the physics engine.
It would appear that from inside OnCollisionEnter2D (or 3D as well), the physics engine has already acted upon it and all the info I get is the result AFTER the collision and not just before.
I was hoping for something like BeforeOnCollisionEnter2D but nothing like that exists.
Any suggestions?
Thanks, Manny
Have you tried using a ray under your object? when the ray is hitting an object under it, return whatever you need about the object. Raycasting
Answer by Baste · May 21, 2015 at 01:37 PM
If you only need this behaviour from a few objects, you could put a script on them that stores the data from the rigidbody every FixedUpdate, and then poll that data after the collision.
So a script like:
PhysicsCachedData : MonoBehaviour {
Vector3 lastVelocity;
Vector3 currentVelocity;
void FixedUpdate() {
lastVelocity = currentVelocity;
currentVelocity = rigidbody.velocity;
//store current and last of all the other properties you're interested in
}
}
and then you could poll it like this:
void OnCollisionEnter(Collider c) {
var cachedData = c.GetComponent<PhysicsCachedData>();
if(cachedData != null) {
//use cachedData.lastVelocity here
}
}
That's really the only thing I can think of. It might be that it's enough to store only data from this frame, if FixedUpdate happens before collisions are resolved - you'll have to check that yourself.
That's what I'm doing right now, except I'm using Update ins$$anonymous$$d of FixedUpdate.
I'm just trying to optimize by not doing so many memory moves needlessly all the time as collisions only happen occasionally.
Thanks for your input.
In continuation to the method above by @Baste one optimization you can do is extrapolate the position of rigidbody to get the expected time of when the next collision might happen and check for physics values for the rigidbody inside FixedUpdate based off that time value.