# How to replicate Unity's Rigidbody.AddForceAtPosition in C++?

I am trying to replicate the function Rigidbody.AddForceAtPosition of Unity in C++, it means, to apply force to a body offset from its center.

How could I achieve that in C++?

• Do you mean C#? Unity doesn't do C++. – Wayne Koorts Mar 23 '16 at 2:44
• No, I am trying to replicate the behavior in a C++ project.But if you have the solution in C#, that is fine too. :) – Ron Mar 23 '16 at 2:57

## 1 Answer

This code is from my own physics engine (C#). It's 2D, but it's just the same in 3D. The forces are simply accumulated, and the rotation (torque) produced is the cross product of the vector from the center of the object to the point and the force applied.

public void ApplyForceAtPoint(Vec2 f, Vec2 point)
{
force += f;
torque += Vec2.Cross(point - position, f);
}

• Thanks a lot! One more thing, how do apply the torque to the rotation of the object? Do you convert it to Quaternion? – Ron Mar 23 '16 at 7:46
• In your integration equations, the torque is multiplied by the inverse of the inertia tensor (which is a 3x3 matrix in 3D), scaled by the delta time and finally added to the angular velocity, which can be written as angVel += (invInertia * torque) * dt. If w = angVel * dt is the angle-axis representation of the rotation as a result of the angular velocity, then to represent this instant's rotation as a quaternion, you can use Euler's formula's extension as follows: q = Quaternion(cos(len(w) / 2), normalized(w) * sin(len(w) / 2)). Cont. in next comment. – EvilTak Mar 23 '16 at 8:06
• The final rotation is then computed by multiplying the rotation for this instance with the original rotation q0. q' = q * q0 If you don't use Quaternions to represent rotations, then you can just straightaway add the euler axis representation w to your rotation vector. – EvilTak Mar 23 '16 at 8:07