I am throwing a projectile with a certain speed and direction.
I would like it to deal damage if the collision occured in the direction of its velocity.
I have tried various calculations in OnCollisionEnter(Collision collision)
I can acquire the normal of the contact but Rigidbody.velocity is already changed the moment OnCollisionEnter is called.
What calculation must I make to determine if the projectile are going in the direction of the collision with the other rigidbody in OnCollisionEnter?
I’m not exactly sure what you’re saying here. Are you worried about things hitting projectiles from behind? Maybe an illustration of what kind of situation you don’t want to trigger damage would be helpful?
Anyway would if help to keep track of the velocity of the projectile from the previous physics update in FixedUpdate()? Maybe compare that with collision.relativeVelocity in some way?
Vector3 lastKnownVelocity;
void FixedUpdate() {
lastKnownVelocity = GetComponent<Rigidbody>().velocity;
}
void OnCollisionEnter(Collision collision) {
// some check against lastKnownVelocity
}
1 Like
Yes that’s the problem I’m trying to fix.
I think your solution works
Your solution only works if the collision has occured after a fixedupdate.
If I spawn a rigibody in a position where it collides with something lastKnownVelocity won’t be set and it creates a bug.
I need to have the velocity before it’s been modified by the collision.
But OnCollisionEnter can be called before FixedUpdate…
Thus setting the lastKnownVelocity in Start/Awake/OnEnable doesn’t work because the Rigidbody.velocity could be changed in between the call of those methods and OnCollisionEnter() by other scripts.
Collision.relativeVelocity is not what I’m looking for because it adds up the 2 colliding object’s velocities together…
How can I get a rigidbody’s velocity before the collision?
@yant Do you have a solution to this problem? Any help would be greatly appreciated