0
\$\begingroup\$

In Unity3D there's a way to add force at a position and a way to get the velocity at a position. I'd like to be able to set the velocity of a rigidbody2d at a local position.

My current solution which is very much WIP and very much wrong is as follows:

            _colliderRigidbody.velocity = _knockbackForce;

            Vector2 dirToCenter = (_colliderRigidbody.position - Position2D).normalized;

            float relativeAngleVel = Vector3.Dot(dirToCenter.normalized, _knockbackForce.normalized);
            bool onRight = Vector3.Cross(dirToCenter, _knockbackForce).z > 0;

            relativeAngleVel = 1.0f - Mathf.Abs(relativeAngleVel);

            relativeAngleVel = onRight ? -relativeAngleVel : relativeAngleVel;

            _colliderRigidbody.angularVelocity = -relativeAngleVel * 50;//lol * 50 because who knows what I'm doing >.<

In regards to the problem I'm trying to solve: I have a 'bullet' which hits a target object, I know the point of impact and the direction the bullet is going so I'd like the velocity at that point of impact to be the same as the bullets.

\$\endgroup\$
  • \$\begingroup\$ Can you give us more information about how you intend to apply this? There are two components that contribute to the velocity of a point on the object: its linear velocity and its angular velocity. For any given value of one, we can produce a compensating value for the other so that the net veliocity at that point is the target value. That means the system is under-determined: we have an infinite variety of possible solutions, so we'll need additional criteria to figure out what combination of linear and angular velocity is appropriate for the case in your game. \$\endgroup\$ – DMGregory Jul 4 '17 at 4:10
  • \$\begingroup\$ @DMGregory Fair point, I added some more info. \$\endgroup\$ – meds Jul 4 '17 at 7:40
  • \$\begingroup\$ The application you describe would more conventionally use an Impulse. Usually the object you're shooting has a different mass than the bullet, so even with perfect energy transfer it will still get a different velocity to respect conservation of momentum. Is this velocity matching a hard requirement, or can we use a more typical impulse instead? \$\endgroup\$ – DMGregory Jul 4 '17 at 11:48

Your Answer

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

Browse other questions tagged or ask your own question.