围绕另一个任意点旋转任意点的问题

时间:2018-06-27 15:44:55

标签: c# unity3d

我编写了以下方法,以在持续时间内围绕任意点旋转任意点一个角度。现在,所讨论的问题不规则地移动,但最终绕到我认为是理想目的地的地方。我需要使它平稳地移动到一定角度。

请注意,这些点与游戏对象无关。

从下图开始,我试图在给定的时间段内将贝塞尔曲线的一个点(用LineRenderer绘制)绕另一点移动一个角度。这些点都不与包含贝塞尔曲线的游戏对象的位置重合。

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;
    }
}

2 个答案:

答案 0 :(得分:1)

您想要的图案就是

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;
    }

答案 1 :(得分:0)

我真的可以为您带来很多帮助,但我可以提供一些有关随时间推移运动的建议。我必须学习的难点是,尽可能避免使用协例程。尽管它们看起来很漂亮,但是它们有点让人困惑,而Unity使用它们的方式与在C#其他领域中使用它们的方式并不完全相同。

只要有可能,我都只使用一个统一类来更新每个框架。它更容易理解和调试。这种情况的缺点是,您要旋转的每个点都需要一个新组件,但这并不重要。

public class PointRotator : MonoBehaviour

{

bool rotating = false;
float rate = 0;
float angle;

Vector3 point;
Vector3 pivot;

public void Rotate(Vector3 point, Vector3 pivot, float duration, float angle)
{
    this.point = point;
    this.pivot = pivot;
    this.rate = angle/duration;
    this.angle = angle;

    rotating = true;
}

public void Update()
{
    if (rotating)
    {
        // use quartonian.Lerp with Time.deltatime here

    //if(angle > quartonian angle){rotating = false)
    }
}

}

尝试类似的方法,看看问题是否消失。否则,您可能需要多研究一些Quartonians,或者由于您是在二维平面中,所以只能手动进行三角测量。

相关问题