0
\$\begingroup\$

Working in Unity, I have a game object which I rotate each frame, like so:

void Update()
{
    transform.Rotate(new Vector3(0, 1, 0) * speed * Time.deltaTime);
}

However, I'm running into problems when it comes to applying a force to rigidbodies that collide with this game objects sphere collider. The effect I'm hoping to achieve is that objects which touch the collider are thrown in roughly the same direction as the object is rotating. To do this, I've tried the following:

Vector3 force = ((transform.localRotation * Vector3.forward) * 2000) * Time.deltaTime;
collision.gameObject.rigidbody.AddForce(force, ForceMode.Impulse);

Unfortunately this doesn't always match the rotation of the object. To debug the issue, I wrote a simple OnDrawGizmos script, which (strangely) appears to draw the line correctly oriented to the rotation.

void OnDrawGizmos()
{
    Vector3 pos = transform.position + ((transform.localRotation * Vector3.forward) * 2);
    Debug.DrawLine(transform.position, pos, Color.red);
}

You can see the result of the OnDrawGizmos function below:

enter image description here

What am I doing wrong?

\$\endgroup\$
2
\$\begingroup\$

The direction of the force applied to a point colliding with your rotating object is the tangent to the sphere, perpendicular to the axis the sphere is rotating on. You should be able to calculate it with the following pseudo-code:

vectorToContact = (pointOfContact - centerOfSphere);
directionOfForce = normalize(cross(vectorToContact, axisOfRotation))

A small detail to keep in mind is that the axisOfRotation will differ depending on whether the rotation is negative or positive, which in turn depends on whether you're in a right- or left-handed coordinate system; Unity, I believe, is left-handed.

To put that another way, let's say your sphere is rotating along the z-axis, (0, 0, 1). You could either provide (0, 0, 1) or (0, 0, -1) to the cross product; both are along the z-axis. Which one you provide will depend on the sign of the rotation. If your object is rotating with a positive speed, you'd use the positive z-axis in the cross product.

Lastly, the magnitude of the force would depend on the speed at which your object is rotating, and if you're feeling adventurous, the coefficient of friction of its surface.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks for such a comprehensive write up! I've implemented your solution and it's working very well. \$\endgroup\$ – ndg Jun 7 '14 at 8:41

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.