Using a rectangle to constrain 2D Player object movement
Basic character movement in 2D (within a bounding rectangle) is a core skill for many 2D games, so this first recipe will illustrate how to achieve these features for a 2D game. The remaining recipes will then build on this approach for 3D games.
Since in Chapter 3, Inventory and Advanced UIs, we created a basic 2D game template, we’ll adapt this game to restrict the movement to a bounding rectangle:
Figure 11.1: Movement of a character within the rectangular area
Getting ready
This recipe builds on the simple 2D mini game called Simple2DGame_SpaceGirl
from the first recipe of Chapter 3, Inventory and Advanced UIs. Start with a copy of this game, or use the provided completed recipe project as the basis for this recipe.
How to do it...
To create a 2D sprite controlled by the user with movement that is limited to within a rectangle, follow these steps:
- Create a new, empty GameObject...