- Home /
Problems reading Rigidbody velocity magnitude
I'm trying to make a boss-level for a 2D game, in which the character gets shot out of a cannon and has to hit the boss. In the boss-script I'm trying to measure the force with which the character hits it, so that I can figure out if it was hard enough for the boss to take damage. My code for this is
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.name == "CannonAmmo"/* && col.gameObject.rigidbody2D.velocity.magnitude >= damageBound*/) {
Debug.Log("Was hit with force " + col.gameObject.rigidbody2D.velocity.magnitude);
}
}
The problem is that the debug-message prints a velocity of anything between about 2 to about 30, for almost the exact same situation :P Any ideas why this might be? As it is now, it's obviously unusable.
Fafner
Untested idea: Save the velocity.magintude each frame. Then use the velocity.magnitude from the previous frame (before the collision). You may have to test and play to get the order right.
I'm with robertbu on this one. You probably need to take the velocity at a point away from the end point. I don't know the internals of the Unity collision system, but they might adjust the velocity for the impact of the collision before sending the OnCollision event (which seems wrong).
Is there any reason you can't use the initial velocity? It seems that you should be in control of the shot out of the cannon and its velocity and thereby able to use that velocity as an indicator of how hard the player hits the boss, unless you have something in the player's path that can slow him down other than gravity.
Thanks, I'm gonna try this! :) supernat, I guess you're right, this might be too complicated for what I'm trying to achieve :P
Answer by Owen-Reynolds · Jan 31, 2014 at 04:53 PM
In this case, you could probably use collision2D.relativeVelocity.magnitude
. It will also count the boss's speed, but that might be more correct (hitting while it moves away would be a little softer.)
Tested, just now: OnCollisionEnter now happens after the physics part is resolved, which seems more correct to me. Often I want to tweak the bounce, like a wall that only sends things sideways, or removes all spin. If OnCollision is called pre-physics, this is way hard and confusing (a 1-frame delay coroutine?)
As robertu points out, maintaining "trailing" vars, if you want more pre-collision stats, isn't that much work.
Ideally, there would be an OnPreCollisionEnter function (but probably just slows down the framework, for virtually no gain.)
Thanks, I was thinking about that, taking the boss' velocity into account as well. I'm gonna try out both suggestions:)