Когда пользователь прекращает вращать корабль, как мне заставить его плавно повернуть назад? - PullRequest
0 голосов
/ 01 февраля 2019

Таким образом, вопрос может быть неясным, но корабль вращается с клавишами со стрелками идеально, но когда клавиши со стрелками отпущены, я хочу, чтобы он повернулся обратно в положение (0, yRotation, 0), но плавно (то же самое движение, для которого пользователь вращает его в первую очередь), есть идеи, как я могу это сделать?

xRotation, yRotation и zRotation все инициализируются в 0.

    float xThrow = CrossPlatformInputManager.GetAxis("Horizontal");


        if(xThrow > 0) {

            transform.rotation = Quaternion.Euler(xRotation, yRotation +     0.6f, zRotation - 0.6f);
            yRotation += 0.6f;
            zRotation -= 0.6f;
                        }

        else if (xThrow < 0)
        {

            transform.rotation = Quaternion.Euler(xRotation, yRotation -     0.6f, zRotation + 0.6f);
            yRotation -= 0.6f;
            zRotation += 0.6f;
        } 

      else {
            transform.rotation = Quaternion.Euler(0f, yRotation,     zRotation);
            while (zRotation > 0) {
              zRotation -= 0.6f;
            }

            while (zRotation < 0) {
            zRotation += 0.6f;
            }
        }

КодЯ написал, возвращает его в требуемое положение вращения, однако он не является гладким и делает это как один кадр.Я хочу добиться этого, но очень плавно, а не в виде одного кадра.

1 Ответ

0 голосов
/ 01 февраля 2019

Если вы хотите сбросить вращение в блоке else, вы должны использовать Coroutine .Внимание, так как я также предполагаю, что вы используете это в Update методе, будьте осторожны, чтобы не запускать несколько подпрограмм.

// set this in the Inspector
public float resetDuration;

// make sure there is only one routine running at once
private bool isResetting;

// ...

    else 
    {
        // if no routine is running so far start one
        if(!isResetting) StartCoroutine(RotateToIdentity());
    }

// ...

private IEnumerator RotateToIdentity()
{
    isResetting = true;

    // I recommend using this for rotations and not do them by manipulating 
    // 3 float values. Otherwise could also Lerp all three float values and use them for the rotation here as well
    var currentRot = transform.localRotation;
    var targetRot = Quaternion.Identity;

    // than use those
    // var currentX = xRotation;
    // var currentY = yRotation;
    // var currentZ = zRotation;

    var timePassed = 0.0f;
    while(timePassed <= resetDuration)
    {
        // interpolate between the original rotation and the target
        // using timePassed / resetDuration as factor => a value between 0 and 1
        transform.rotation = Quaternion.Lerp(currentRot, targetRot, timePassed / resetDuration);

        // or with your rotations
        // xRotation = Mathf.Lerp(currentX, 0, timePassed / resetDuration);
        // yRotation = Mathf.Lerp(currentY, 0, timePassed / resetDuration);
        // zRotation = Mathf.Lerp(currentZ, 0, timePassed / resetDuration);
        // transform.rotation = Quaternion.Euler(xRotation, yRotation, zRotation);

        // add passed time since last frame
        timePassed += Time.deltaTtime;

        // return to the mein thread, render the frame and go on in the next frame
        yield return null;
    }

    // finally apply the target rotation just to be sure to avoid over/under shooting
    transform.rotation = targetRot;

    // if you really want to go on using xRotation, yRotation and zRotation also reset them when done
    xRotation = 0;
    yRotation = 0;
    zRotation = 0;

    isResetting = false;
}

Вы также должны рассмотреть возможность использования Time.deltaTime для всех вашихповороты.

Одно из преимуществ использования 3 отдельных lerps: как только пользователь снова начнет взаимодействовать, он может прервать процедуру сброса

if(xThrow > 0) 
{   
    StopAllCoroutines();
    isResetting = false;

    // ...
}
else if (xThrow < 0)
{
    StopAllCoroutines();
    isResetting = false;

    // ...
}

// ---
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...