Player control of a 2D GameObject (and limiting the movement within a rectangle)
While the rest of the recipes in this chapter are demonstrated in 3D projects, basic character movement in 2D and also limiting the movement to a bounding rectangle, are core skills for many 2D games, and so this first recipe illustrates how to achieve these features for a 2D game.
Since in Chapter 3, Inventory UIs, we already created a basic 2D game, we'll adapt this game to restrict the movement to a bounding rectangle:

Getting ready
This recipe builds on a simple 2D game called the Simple2DGame_SpaceGirl
mini game from the first recipe of Chapter 3, Inventory UIs. Start with a copy of this game, or use the provided completed recipe project as the basis for this recipe. You can download the completed project from https://github.com/dr-matt-smith/unity-cookbook-2018-ch03.
How to do it...
To create a 2D sprite controlled by the user with a movement that is limited to within a rectangle, follow these steps:
- Create...