AddForce to object based on direction of the colliding object

I might have formulated the question incorrectly. I’m not quite sure how to title this question.

I have been struggling with this for about two weeks. I tried my best to avoid asking a question. But I do not seem to have an other choice.

I’ve got a ball which can be shot by a different object. If the object collides with the ball, there will be force added to the ball based on the speed of the colliding object and the direction. However, I can’t seem to get a proper way for the direction to work.

I’ve been using rigidbody.velocity to determ the direction. But that’s not working as intended, especially because of the y-axis.

I’ve tried to find different methods, but I can’t seem to find a working one.

What goes wrong

If the object hits the ball, the ball will move to the direction the colliding object is moving to. But no force will be added if it’s not moving perfectly forward. I can’t seem to figure out how to do this on the proper way. Maybe I would have to do some calculations in the Update method? I’m not sure. Maybe there is a more simple way to do this.

Anyway, this is the code I have been using so far:

OnCollisionEnter

``````if (collision.gameObject == GObject) {
BallRB.AddForce ( GObjectRB.velocity * (speed * fForce), ForceMode.Impulse);
}
``````

Speed calculation - FixedUpdate

``````speed = (GObject.transform.position - lastPosition).magnitude;
lastPosition = GObject.transform.position;
``````

I hope someone is able to help me out of my misery!

First off velocity is speed with a direction, so you don’t actually need to calculate speed. In the `AddForce` method try `velocity.direction * fForce`, and for the ForceMode, I don’t thing you want impulse; impulse is based on mass so more impulse needs to be applied to move a heavier object the same distance and the objects moving in opposite direction. What you want is `VelocityChange` that ignores the mass, and is applied in an instant, just like when an object is reflected. If you want to use Impulse then you have to calculate the magnitude of the force based on the `∆momentum = ∆velocity x mass`.

P.S. You shouldn’t use PascalCase for local variables, and fields, only for static variables, and methods. It’s not a big deal but helps in readability of the code, and is kinda an convention. Use camelCase instead.