2
\$\begingroup\$

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++?

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

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);
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks a lot! One more thing, how do apply the torque to the rotation of the object? Do you convert it to Quaternion? \$\endgroup\$ – Ron Mar 23 '16 at 7:46
  • \$\begingroup\$ 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. \$\endgroup\$ – EvilTak Mar 23 '16 at 8:06
  • \$\begingroup\$ 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. \$\endgroup\$ – EvilTak Mar 23 '16 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.