Adding a target

In our shooting gallery, we will need to have something to shoot. In this case, we will need to create a target, which the player can shoot:

  1. Create an empty game object by going to the Hierarchy tab and selecting Create | Empty Game object. Rename that object Target and change its Position to 0, 0,-4 so it'll be on top of other objects.
  2. Add the wooden stick and the duck_outline_brown sprites to the Target object, giving the duck a Position of 0, 1.1,0 to place it on top of the stick.
  3. We want the player to be able to touch the duck so next we will need to add a Polygon Collider 2D component to the duck_outline_brown object:
    Adding a target

Animating the duck using Unity's animation system

  1. Now, let's make it so that our duck will animate when we click on it, but before we do it, we first need to add a base animation for it to use. To do this, open up the Animation tab by going to Window | Animation. This will open the Animation tab by itself.
  2. Next, from the Hierarchy tab, select the Target object and then from the Animation window, click on the Create button on the right-hand side:
    Animating the duck using Unity's animation system
  3. It will ask you where you want to save your animation. In this case, go to the Animations folder we created earlier and then give it a name of Idle before saying OK.
  4. This animation we don't want to change due to the fact that we want it to not move, so let's click on the Idle drop-down and create a new clip, which will create a new animation and we will name Flip.
  5. Once created, move the timeline to the 10th frame (0:10). From there, change the Target object's Y Rotation to 90. Select the duck_outline_brown object and change its sprite to the duck_outline_back image. Then, create another keyframe at the 20th frame with a Y Rotation of 180.
  6. This animation currently will loop itself, which will look incorrect on our end, so let's fix that. Go to the Project tab, open the Animations folder, and select the Flip animation. From the Inspector tab, uncheck the Loop Time property. This will cause the animation to play once and then stop at the end, which is exactly what we want.

Playing Unity animations via code

Now that we have the animation working, let's make it so that we play the animation via code:

  1. Go to the Project tab, open up the Scripts folder, and from there, create a new script named TargetBehaviour. Inside it, use the following script:
    using UnityEngine;
    using System.Collections;
    
    public class TargetBehaviour : MonoBehaviour {
    
        private bool beenHit = false;
        private Animator animator;
        private GameObject parent;
    
        void Start()
        {
            parent = transform.parent.gameObject;
            animator = parent.GetComponent<Animator>();
        }
    
        /// <summary>
        /// Called whenever the player clicks on the object.
        /// only works if you have a collider on the object
        /// </summary>
        void OnMouseDown()
        {
            // Is it valid to hit it
            if (!beenHit)
            {
                beenHit = true;
                animator.Play("Flip");
            }
        }
    }

    This code will play the Flip animation on our target once we click on it. Note that the animator variable uses the object's parent. We need to do this because our collider is attached to the duck itself, not the Target object.

  2. Save the script and then go to the duck_outline_brown image and then attach the Target Behavior to it.
  3. Save the scene and play the game. Now you can click on the sprite:
    Playing Unity animations via code

We have the animation playing correctly! This is a great start.

Animation using iTween

Being able to use Unity's built-in animation system is great and can be quite useful if you want to modify many different properties at once. However, if you're only modifying a single property or you want to animate something purely via code, you can also make use of a tweening library where given a start and an end the library will take care of all the work in the middle to get it there within a time and speed you specify.

One of my favorite tweening libraries is PixelPlacement's iTween, which is open source and useable for free in commercial and noncommercial projects.

  1. Open up the Asset Store tab by going to Window | Asset Store. Type in iTween from the search bar at the top and then press Enter:
    Animation using iTween
  2. If the Asset Store tab is too small for you, as it is here, feel free to drag it out of the middle section and resize until it looks nice for you.
  3. From there, you'll be brought to a list of items with the first one being iTween. Select it and you should be brought to iTween's product page. Click on the Download button:
    Animation using iTween
  4. From there, you'll be asked to log in to your Unity account that you created when you installed Unity. If you don't have one, feel free to click on Create Account and do so. Once logged in, click on Download once again, and if it doesn't happen automatically, click on the Import button.
  5. You should see an Import Unity Package window pop up. From there, you can check or uncheck whatever files you wish to keep. I will just be using iTween.cs, but the others may be useful to you and you should wish to use them on your own. Once you're finished selecting, click on the Import button:
    Animation using iTween
  6. We don't need the Asset Store anymore, so go ahead and close it out. You'll note that now we have the files we have selected inside our Project tab:
    Animation using iTween
  7. Now that we have iTween included in our project, we can now use it inside of our code. Open up our Target Behavior script in your IDE of choice and add the following variable:
    private bool activated;
  8. Next, add in the following function:
    public void ShowTarget()
    {
        if (!activated)
        {
            activated = true;
            beenHit = false;
            animator.Play("Idle");
    
            iTween.MoveBy(parent, iTween.Hash("y", 1.4,
                                              "easeType", "easeInOutExpo",
                                              "time", 0.5
                                               ));
        }
    
    }

From here, we'll see our first function that we are calling from iTween the MoveBy function. This takes in two parameters—the first being the object we wish to move and the second being a Hash or hashtable. A hashtable is a data structure that creates an associative array such that certain keys will be mapped to certain values. In iTween, their implementation takes in sets of two with the first being a property and then second being the value we want it to be.

Note

For more information on hashtables, check out http://en.wikipedia.org/wiki/Hash_table.

For more information on getting started with iTween, check out http://itween.pixelplacement.com/gettingstarted.php.

  1. Now that we have this function, for testing purposes let's add to the end of the Start function the following line: ShowTarget();
  2. Save your project and play the game!.
    Animation using iTween

Once the game starts, you'll note that the duck flies up in the y axis by the amount we specified via the hash!

  1. Now, let's make it so that the duck will move back down once we click on it. Add the following variable to the class:
    private Vector3 originalPos;
  2. Afterwards, add the following line inside the Start function so that we initialize it:
    originalPos = parent.transform.position;
  3. Then, add in this new function:
    public IEnumerator HideTarget()
    {
        yield return new WaitForSeconds(.5f);
    
        // Move down to the original spot
        iTween.MoveBy(parent.gameObject, iTween.Hash(
        "y", (originalPos.y – parent.transform.position.y),"easeType", "easeOutQuad", "loopType", "none", "time", 0.5, "oncomplete", "OnHidden", "oncompletetarget", gameObject));
    }

    Note

    Note that in this case, we added the oncomplete and oncompletetarget parameters to our hash map. oncomplete will call a function (in this case, OnHidden, which we will create after this) after the amount of time has elapsed and "oncompletetarget" will be what object iTween will look for the function with a name of whatever was provided in the oncomplete portion. This is only needed if the object you're animating is not the object that iTween is called on.

  4. Add in the OnHidden function:
    /// <summary>
    /// After the tween finishes, we now make sure we can be shown
    /// again. 
    /// </summary>
    void OnHidden()
    {
        //Just to make sure the object's position resets
        parent.transform.position = originalPos;
        activated = false;
    }
  5. And finally, we need to update the OnMouseDown button so that we will only flip when the animation is valid by adding in the following bolded code:
    void OnMouseDown()
    {
        // Is it valid to hit it
        if (!beenHit && activated)
        {
            beenHit = true;
            animator.Play("Flip");
            StartCoroutine(HideTarget());
        }
    }
  6. Save your level and project and start up the game!
    Animation using iTween
  7. Our sprite pops up at the beginning and once we click on it:
    Animation using iTween

It flips and falls down, perfect!

Creating moving targets

Now we have our duck, and it can come up and down, it also needs to move rather than just stay in place:

  1. First, let's make it so we can do something once the duck has risen all the way up. To do this, update the ShowTarget function to the following:
    public void ShowTarget()
    {
        if (!activated)
        {
            activated = true;
            beenHit = false;
            animator.Play("Idle");
    
            iTween.MoveBy(parent, iTween.Hash("y", 1.4, "easeType", "easeInOutExpo", "time", 0.5, "oncomplete", "OnShown", "oncompletetarget", gameObject));
        }
    
    }
  2. Now, let's add the OnShown function so that after the object has popped up, it can start moving:
        void OnShown()
        {
            StartCoroutine("MoveTarget");
        }
  3. Now, before we write the MoveTarget function, let's add in the variables needed to have our player move correctly:
        public float moveSpeed = 1f;    // How fast to move in
        // x axis
        public float frequency = 5f;    // Speed of sine 
        // movement
        public float magnitude = 0.1f;  // Size of sine 
        // movement
  4. Now, let's create a coroutine to cause the target to move up and down over time while going towards the edge of the screen:
    IEnumerator MoveTarget()
    {
        var relativeEndPos = parent.transform.position;
    
        // Are we facing right or left?
        if (transform.eulerAngles == Vector3.zero)
        {
            // if we're going right positive
            relativeEndPos.x = 6;
        }
        else
        {
            // otherwise negative
            relativeEndPos.x = -6;
        }    
    
        var movementTime = Vector3.Distance(parent.transform.position, relativeEndPos) * moveSpeed;
    
        var pos = parent.transform.position;
        var time = 0f;
    
        while (time < movementTime)
        {
            time += Time.deltaTime;
    
            pos += parent.transform.right * Time.deltaTime * moveSpeed;
            parent.transform.position = pos + (parent.transform.up * 
            Mathf.Sin(Time.time * frequency) * magnitude);
    
            yield return new WaitForSeconds(0);
        }
    
        StartCoroutine(HideTarget());
    }

Math is a game developer's best friend, and here we are using sin (pronounced sine) by using the Mathf.Sin function.

Taking the sin of an angle number gives you the ratio of the length of the opposite side of the angle to the length of the hypotenuse of a right-angled triangle.

If this didn't make any sense to you, don't worry. The neat feature of sin is that as the number gets larger, it will continuously give us a value between 0 and 1 that will go up and down forever, giving us a smooth repetitive oscillation.

Note

For more information on sine waves, visit http://en.wikipedia.org/wiki/Sine_wave.

This mathematical principle could be used in a lot of effects, such as having save points/portals bob up and down, or any kind of object you would want to have slight movement or some special FX:

  1. Next, we need to update the OnMouseDown function so that the horizontal movement won't happen anymore if we click on the duck:
    /// <summary>
    /// Called whenever the player clicks on the object. Only works if
    /// you have a collider
    /// </summary>
    void OnMouseDown()
    {
        // Is it valid to hit it
        if (!beenHit && activated)
        {
            beenHit = true;
            animator.Play("Flip");
    
            StopAllCoroutines();
    
            StartCoroutine(HideTarget());
        }
    }
  2. Save your project and start the game!
    Creating moving targets

Now our target will move towards our edge with a slight bobbing motion and will automatically hide itself afterwards if it is not clicked! Perfect!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset