Unity3d根据俯仰,横滚和偏航角度列表平滑地旋转对象

洛希特·佩萨帕蒂

我想根据从API调用获得的角度(俯仰,横滚和偏航)列表平滑地旋转对象(平面)。响应对象是下面Rootresponse

public class ResponseData
{
    public List<int> x; //roll
    public List<int> y; //yaw
    public List<int> z; //pitch
}

public class RootResponse
{
    public ResponseData data;
    public string status; //status of the api call
}

我试图使用下面的代码使用while循环遍历FixedUpdate方法中每一帧的值这将引发“ ArgumentOutOfRange”异常。

如果我根据文档使用transform.Roatate或Quarternion角度,则只能获得最终位置。

在这种情况下,我可以选择的最佳方法是什么?

void FixedUpdate(){
    if(shouldUpdate) { //set to true for a success response from the api call
        while(ind < dataLen) {
            transform.position = Vector3.MoveTowards(new Vector3(batData.x[ind], batData.y[ind], batData.z[ind]), new Vector3(batData.x[ind+1], batData.y[ind + 1], batData.z[ind + 1]), speed * Time.deltaTime);
            ind++; //to increment the index every frame
        }
    }
}
鲁济姆

您(可能)不希望将一帧范围内的所有旋转与旋转速度无关。

相反,您应该跟踪遍历该帧队列的过程中正在旋转多少,如果遇到这种情况,请退出while循环。

public float maxAngleRotatePerFrame = 5f;

void FixedUpdate(){
    if(shouldUpdate) { //set to true for a success response from the api call
        // Keep track of how far we've traveled in this frame.
        float angleTraveledThisFrame = 0f;

        // Rotate until we've rotated as much as we can in a single frame, 
        // or we run out of rotations to do.
        while (angleTraveledThisFrame < maxAngleRotatePerFrame && ind < dataLen) {
            // Figure out how we want to rotate and how much that is
            Quaternion curRot = transform.rotation;
            Quaternion goalRot = Quaternion.Euler(
                    batData.x[ind],
                    batData.y[ind],
                    batData.z[ind]
                    );
            float angleLeftInThisInd =  Quaternion.Angle(curRot, goalRot);

            // Rotate as much as we can toward that rotation this frame
            float curAngleRotate = Mathf.Min(
                    angleLeftInThisInd, 
                    maxAngleRotatePerFrame - angleTraveledThisFrame
                    );

            transform.rotation = Quaternion.RotateTowards(curRot, goalRot, curAngleRotate);

            // Update how much we've rotated already. This determines
            // if we get to go through the while loop again.
            angleTraveledThisFrame += curAngleRotate;

            if (angleTraveledThisFrame < maxAngleRotatePerFrame ) {  
                // If we have more rotating to do this frame,
                // increment the index.
                ind++;

                if (ind==dataLen) {
                    // If you need to do anything when you run out of rotations, 
                    // you can do it here.
                }
            }
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章