Avançar para o conteúdo principal

Unity 3D Coroutines Part II

Coroutines are functions useful to implement tasks that need to happen across multiple frames.

In this post we will see how to make the camera animate from one point to other across some time, the amount of time will be set in a variable so it can be changed.

The function will be called when the user press the space bar.

void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if(func!=null)
                StopCoroutine(func);
            func = StartCoroutine(smoothMoveCamera());// moveCamera());
        }
}

We need some variables in the class:
    public float duration = 2.0f;
    public float xStart = -5.0f;
    public float xFinish = 5.0f;
    Coroutine func;

The first variable sets the number of seconds the animation will endure. Second is the start point and the third the final point, both are points in the x axis.
Then there's a reference to the coroutine so we can stop it if needed.

The coroutine code is this:
    IEnumerator smoothMoveCamera()
    {
        float speed = 1 / duration;
        float percent = 0;
        while (true)
        {
            percent += speed*Time.deltaTime;
            transform.position = new Vector3(Mathf.Lerp(xStart, xFinish, percent),1,-10);
            yield return null;
            if (percent >= 1) break;
        }
    }

We start by calculating the speed of the camera by dividing 1 by the duration. This is the speed per second, inside the loop we multiply by the deltaTime to adjust to the time it took to render the last frame.
Then we calculate the new position using the Lerp function using the percentage of the time completed to lerp between the starting point and the end point.
After the new position is set there's the yield statement which return the execution to the Unity engine so the frame get's rendered. After that we check to see if the percentage is 1 and if so the execution ends, because we are done.

Comentários

Mensagens populares deste blogue

Single Page App with C# WPF/XAML

 In this post we are going to create a single page app. The app will have multiple pages that get rendered in the main window. We will be using Visual Studio, C#, WPF and XAML. Let's start by creating a new project in Visual Studio of this type: Next, in the MainWindow, we define the interface structure. On the left side we place a menu and on the right side a DockPanel with a Frame in it. The Frame is the element that is used to render de pages content. Now let's add the new pages. In this example I will add two pages. Click in the Solution Explorer with the mouse right button, then choose Add and Page. The project looks like this. The app content goes on the recently create pages. Because this is just an example I will just change the background color and add a small text. Page1 Page2 Finally the code. Back to the MainWindow we need to create the click events on the menu items. So, in the MenuItem line add the click event and pick New Event Handler. If that option doesn't...

C# IEnumerator and IEnumerable interfaces

In this article we will learn how to use the IEnumerator interface to allow you to use a foreach loop in a data set or collection. Most collections (lists and others) already implement the interface, but in this case we will customize the way we browse through the list. When we use code like this: foreach(Class c in Collection) { ... } The compiler convertes this code in something like this: IEnumerator cc = Collection.GetEnumerator() while(cc.MoveNext()) { c=(Class)cc.Current; ... } Implementing the IEnumerable interface means that the class implements a version of the GetEnumerator () function that must return a class that implements the IEnumerator interface. Let's explore an example. We start with the client class: This class will allow you to store customer data, and there is a field to indicate whether the customer is still active or not. Next is a class that defines a client list and implements the IEnumerable interface that returns an object...

Let's make a car in Unity 3D

In this post we will make a simple car in Unity 3D. The Unity 3D physics engine is used in order to give the car a real behavior. This are the steps: [1] - Create a new Project