0
\$\begingroup\$

I'm using the function Transform.RotateAround in order to make my player rotate around objects in my game, it's the main feature.

The thing is, when I'm making my levels harder and make the objects (that the player rotates around) dynamic and add some movement on the X & Y axis, the rotation movement is inconsistent, obviously, since the function recalculates each frame a different pivot to rotate around, the player distance from the object changes and not staying static throughout the rotation cycles.

The question is, is there a way to get around this and make the player rotate around the object in a static, permanent distance from the object even though it's moving?

Maybe by predicting the movement of the object or somehow "diffusing" the effect of the object movement..?

Any comment would be helpful.

Thanks in advance!

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You can store your current pivot object, direction from it, and distance away in member variables.

Overwrite these values when you start rotating around a new pivot, but then keep the distance variable fixed at that value for future updates.

In your Update (or LateUpdate, if you want to be sure this runs after any Update scripts or animations that move your pivot objects around), rotate your direction, scale it by your distance, and add it to the pivot position to find your new location relative to it.

Here's one way that could look:

public class RotateAround : MonoBehaviour {

    public float rotationSpeed = 90f;

    Transform _pivot;
    Vector3 _offsetDirection;
    float _distance;

    public void SetPivot(Transform pivot) {
        if (pivot != null) {
            _pivot = pivot;
            _offsetDirection = transform.position - pivot.position;
            _distance = _offsetDirection.magnitude;
        } else {
            _pivot = null;
        }
    }

    void Update() {
        if (_pivot == null) return;

        Quaternion rotate = Quaternion.Euler(0, 0, rotationSpeed * Time.deltaTime);

        _offsetDirection = (rotate * _offsetDirection).normalized;

        transform.position = _pivot.position + _offset * _distance;
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Worked like a magic. Awesome! Thanks so much. \$\endgroup\$ Jan 18, 2021 at 22:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .