Unity3d Плавное вращение объекта на основе списка углов тангажа, крена и рыскания - PullRequest
0 голосов
/ 14 ноября 2018

Я хочу плавно повернуть объект (плоскость) на основе списка углов (Pitch, Roll и Yaw), полученных из вызова 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
}

Я попытался перебрать значения каждого кадра в методе FixedUpdate , используя цикл while с использованием приведенного ниже фрагмента кода. Это создает исключение "ArgumentOutOfRange" .

Если я использую transform.Roatate или Quarternion angle согласно документации, я могу получить только окончательную позицию.

Какой наилучший подход я могу выбрать в этом случае?

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

1 Ответ

0 голосов
/ 14 ноября 2018

Вы (вероятно) не хотите применять все повороты в пределах одного кадра независимо от скорости вращения.

Скорее, вы должны следить за тем, сколько вы вращаете во время работы с очередью в этом кадре, и выходить из цикла 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.
                }
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...