Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

2D Animation and Physics

Since Unity 4.6 in 2014, Unity has shipped with dedicated 2D features, and in this chapter, we will present a range of recipes that introduce the basics of 2D animation to help you understand the relationships between the different animation elements.

In Unity 2D, animations can be created in several different ways – one way is to create many images, each slightly different, which give the appearance of movement frame by frame.

A second way to create animations is by defining keyframe positions for individual parts of an object (for example, the arms, legs, feet, head, and eyes) and getting Unity to calculate all the in-between positions when the game is running:

Figure 8.1: Overview of animation in Unity

Both sources of animations become animation clips in the Animation panel. Each animation clip then becomes a state in an Animator Controller State Machine. We can also duplicate states based on animation clips, or create new...

Flipping a sprite horizontally – the DIY approach

Perhaps the simplest 2D animation is a simple flip, from facing left to facing right, facing up to facing down, and so on. In this recipe, we’ll add a cute bug sprite to the scene and write a short script to flip its horizontal direction when the Left and Right arrow keys are pressed:

Figure 8.2: Example of flipping a sprite horizontally

Getting ready

For this recipe, we have prepared the image you need in a folder named Sprites in the 08_01 folder.

How to do it...

To flip an object horizontally with arrow key presses, follow these steps:

  1. Create a new Unity 2D project.

    If you are working on a project that was originally created in 3D, you can change the default project behavior (for example, new Sprite Texture additions and Scene mode) to 2D by going to Edit | Project Settings | Editor and then choosing 2D for Default Behavior Mode in the Inspector panel:

  2. ...

Flipping a sprite horizontally – using Animator State chart and transitions

In this recipe, we’ll use the Unity animation system to create two states corresponding to two animation clips.

Unity Animator Controllers manage a State Machine to control how and when an animated GameObject should change. At any point in time, a GameObject with an Animator Controller component is either in one state or transitioning between states.

We’ll have one script class that changes localScale according to which animation state is active. There will also be a second script class, which will map the arrow keys to the Horizontal input axis values as a parameter in the State Machine, which will drive the transition from one state to the other.

While this may seem like a lot of work, compared to the previous recipe, such an approach illustrates how we can map from input events (such as key presses or touch inputs) to parameters and triggers in a State Machine.

Getting...

Animating body parts for character movement events

In the previous recipe, we used the Unity animation tool to alter the transition of a sprite based on input. In this recipe, we’ll learn how to animate the hat of the Unity PotatoMan character in response to a jumping event using a variety of animation techniques, including keyframes and transforms.

Getting ready

For this recipe, we have prepared the files you need in the 08_03 folder.

How to do it...

To animate body parts for character movement events, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided PotatoManAssets package into your project.
  3. Increase the size of Main Camera to 10.
  4. Set up the 2D gravity setting for this project – we’ll use the same setting that’s provided in Unity’s 2D platform tutorial – that is, a setting of Y= -30. Set 2D gravity to this value by going to Edit | Project Settings | Physics 2D and changing...

Creating a three-frame animation clip to make a platform continually animate

In this recipe, we’ll make a wooden-looking platform continually animate, moving upward and downward. This can be achieved with a single three-frame Animation Clip (starting at the top, then positioned at the bottom, and finally back at the top position). Note that each frame is a static position and that we will employ the animation technique known as in-betweening to create the necessary movement:

Figure 8.29: Example of a moving platform game

Getting ready

This recipe builds on the previous one, so make a copy of that project and work on the copy for this recipe.

How to do it...

To create a continually moving animated platform, follow these steps:

  1. Drag an instance of the platformWoodBlocks sprite from the Project | Sprites folder into the scene. Position this GameObject at (-4, -5, 0) so that these wood blocks are neatly to the left and slightly below the wall...

Making a platform start falling once stepped on using a Trigger to move the animation from one state to another

In many cases, we don’t want an animation to begin until some condition has been met, or some event has occurred. In these cases, a good way to organize an Animator Controller is to have two animation states (clips) and a Trigger on the transition between the clips. We can use code to detect when we want the animation to start playing, and at that time, we send the Trigger message to the Animator Controller, causing a Transition to start.

In this recipe, we’ll create a water platform block in our 2D platform game. Such blocks will begin to slowly fall down the screen as soon as they have been stepped on, and so the player must keep on moving; otherwise, they’ll fall down the screen with the blocks too!

Figure 8.32: Example of a falling platform

Getting ready

This recipe builds on the previous one, so make a copy of that project and...

Creating animation clips from sprite sheet sequences

The traditional method of animation involved hand-drawing many images, each slightly different, which were displayed quickly frame by frame to give the appearance of movement. For computer game animation, the term sprite sheet is given to an image file that contains one or more sequences of sprite frames. Unity provides tools to break up individual sprite images into large sprite sheet files so that individual frames, or sub-sequences of frames, can be used to create animation clips that can become states in Animator Controller State Machines. In this recipe, we’ll import and break up an open source monster sprite sheet into three animation clips for Idle, Attack, and Death, as follows:

Figure 8.37: An example of a sprite sheet

Getting ready

For all the recipes in this chapter, we have prepared the sprite images you need in the 08_06 folder. Many thanks to Rosswet Mobile for making these sprites available...

Creating a platform game with Tiles and Tilemaps

Unity has introduced a set of Tile features that makes creating tile-based scenes quick and easy. A Tile Grid GameObject acts as the parent to Tilemaps. These are the GameObjects that Tiles are painted on, from the Tile Palette panel.

Sprites can be made into Tile assets, and a collection of Tiles can be added to form a Tile Palette, which we can use to paint a scene:

Figure 8.44: Example of using Tilemapper and GameArt2D-supplied sprites

It also offers powerful, scripted Rule Tiles that enhance the Tile brush tools, automatically adding the top, left, right, and bottom edge Tiles as more Grid elements are painted with Tiles. Rule Tiles can even randomly choose from a selection of Tiles under defined conditions. You can learn more at https://unity3d.com/learn/tutorials/topics/2d-game-creation/using-rule-tiles-tilemap.

In this recipe, we’ll create a simple 2D platformer by building a Grid-based scene using...

Using sprite placeholders to create a simple physics scene

Unity offers physics for 2D scenes by providing Colliders, Rigidbodies, gravity, and so on, just as it does for 3D scenes. In this recipe, we’ll create a 2D mountain-style landscape made up of some colored triangles, and then have some square blocks fall down due to gravity into one of the low dips where two triangles overlap. Rather than using images for our sprites, we’ll learn how to use 2D geometric sprite placeholders, a feature in Unity allowing for quick prototyping and scene layouts, where the placeholder sprites can easily be replaced with texture images later. The following screenshot illustrates the starting and ending locations of the square blocks as they fall down and collide with the triangular landscape sprites:

Figure 8.51: A physics scene where 2D squares fall into a dip in the landscape

Getting ready

We’ll create everything from scratch in Unity for this recipe, so no...

Editing polygon Colliders for more realistic 2D physics

In this recipe, we will address the issue of the simple geometric polygon Colliders used as sprite placeholders not matching the final image sprite that replaces the placeholder. This will allow you to use polygon Colliders to approximate the shape of any image outline you might use in your game.

Getting ready

This recipe builds on the previous one, so make a copy of that project and work on the copy for this recipe. We’ll also be using the Enemy Bug image from the first recipe in this chapter, which can be found in a folder named Sprites in the 08_01 folder.

How to do it...

To edit polygon Colliders for more realistic 2D physics, follow these steps:

  1. Copy the project from the previous recipe and use this copy for this recipe.
  2. If you haven’t done so already, import the Enemy Bug image from the provided assets. Then, in the Inspector panel, for each Square GameObject, change the sprite...

Creating an explosionForce method for 2D physics objects

For 3D games, the Rigidbody component has a useful method called AddExplosionForce(...) that will cause an object to look as if it explodes from a given position. However, there is no such method for Rigidbody2D components. In this recipe, we’ll write an extension method for the Rigidbody2D class so that we can add an explosionForce method for 2D objects.

Thanks to Swamy for posting the code for the Rigidbody2D extension class’s explosion force on Unity Forum (Nov. 21, 2013), which this recipe is based on:

Figure 8.60: Bugs being violently forced away from an invisible explosion point

Getting ready

This recipe builds on the previous one, so make a copy of that project and work on the copy for this recipe.

How to do it...

To create an explosionForce method for 2D physics objects, follow these steps:

  1. Copy the project from the previous recipe, and use this copy for this recipe...

Clipping via Sprite Masking

Clipping is the computer graphics term for choosing which parts of a graphical object to display or hide. In 2D graphics, it’s very common to use one image to define parts of a screen to either only show other images or to never show other images. Such an image is known as an image mask. In this recipe, we’ll use two related images. One is an image of the inside of a room, showing a panel out to a night skyscape. The second image is transparent, except for the rectangle where the panel is. We’ll use the second image to only allow other sprites to be seen when they pass by the rectangle panel. The following figure shows how we can only see the parts of the moving blue bird sprite when it is overlapping with the rectangle panel:

Figure 8.62: Image mask being used to only show the bird when it flies through the window rectangle area of the screen

Getting ready

For this recipe, we have prepared the files you need in the...

Further reading

Take a look at the following links for useful resources and sources of information regarding the 2D features provided by Unity:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy