Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issues rotating an arbitrary point around another arbitrary point [duplicate]

Tags:

c#

unity3d

I have written the following methods to rotate an arbitrary point around another arbitrary point by an angle over a duration. The point in question now moves erratically, but ends up around where I believe is the desired destination. I need to get it to move smoothly to the angle.

Please note that the points are independent of a game object.

From the diagram below, I am trying to move one point of a bezier curve (drawn with a LineRenderer) around another point by an angle over a given period of time. None of these points coincide with the position of the game object which contains the bezier curve. 


enter image description here

IEnumerator runMovement()  {

    yield return new WaitForSeconds(2.0f);
    Vector2 pivot = points[3];

    StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f));

}

   IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle)
{
    float currentTime = 0.0f;
    float ourTimeDelta = 0;
    Vector2 startPos = points[0];

    ourTimeDelta = Time.deltaTime;
    float angleDelta = angle / duration; //how many degress to rotate in one second

    while (currentTime < duration)
    {
        currentTime += Time.deltaTime;
        ourTimeDelta = Time.deltaTime;

        points[0] = new Vector2(Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) - Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.x,
                                                        Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) + Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.y);

        yield return null;
    }
}
like image 612
TenOutOfTen Avatar asked Nov 07 '22 05:11

TenOutOfTen


1 Answers

The pattern you want is just

public IEnumerator HowToSmoothly()
    {
    // move "X" from value "A" to value "B"

    float duration = 2.5f;
    float delta = B - A;

    float startTime = Time.time;
    float finishTime = Time.time+duration;

    while(Time.time<finishTime)
        {

        float soFarTime = Time.time-startTime;
        float fractionThisFrame = soFarTime / duration;
        float valueThisFrame = A + delta * fractionThisFrame;

        X = valueThisFrame
        if (X > B) X = B;

        yield return 0;
        }

    X = B;
    yield break;
    }
like image 109
Fattie Avatar answered Nov 17 '22 07:11

Fattie