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 GUI, we already have a basic 2D game, we'll adapt this game to restrict the movement to a bounding rectangle.

Player control of a 2D GameObject (and limiting the movement within a rectangle)

Getting ready

This recipe builds on a simple 2D game called Creating the Simple2DGame_SpaceGirl mini-game from Chapter 3, Inventory GUI. 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 the movement that is limited within a rectangle, follow these steps:

  1. Create a new empty GameObject named corner_max, and position it somewhere above and to the right of the GameObject called Player-girl1. With this GameObject selected in the Hierarchy view, choose the large yellow oblong icon, highlighted in the Inspector panel.
    How to do it...
  2. Duplicate the corner_max GameObject by naming the clone as corner_min, and position this clone somewhere below and to the left of the player-spaceGirl1 GameObject. The coordinates of these two GameObjects will determine the maximum and minimum bounds of movement, permitted for the player's character.
  3. Modify the C# Script called PlayerMove to declare some new variables at the beginning of the class:
    public Transform corner_max;
    public Transform corner_min;
    private float x_min;
    private float y_min;
    private float x_max;
    private float y_max;
  4. Modify the C# Script called PlayerMove so that the Awake() method now gets a reference to the SpriteRenderer, and uses this object to help setup the maximum and minimum X and Y movement limits:
    void Awake(){
      rigidBody2D = GetComponent<Rigidbody2D>();
      x_max = corner_max.position.x;
      x_min = corner_min.position.x;
      y_max = corner_max.position.y;
      y_min = corner_min.position.y;
    }
  5. Modify the C# Script called PlayerMove to declare a new method called KeepWithinMinMaxRectangle():
      private void KeepWithinMinMaxRectangle(){
        float x = transform.position.x;
        float y = transform.position.y;
        float z = transform.position.z;
        float clampedX = Mathf.Clamp(x, x_min, x_max);
        float clampedY = Mathf.Clamp(y, y_min, y_max);
        transform.position = new Vector3(clampedX, clampedY, z);
      }
  6. Modify the C# Script called PlayerMove so that, after having done everything else in the FixedUpdate()method, a call will finally be made to the KeepWithinMinMaxRectangle() method:
      void FixedUpdate(){
        float xMove = Input.GetAxis("Horizontal");
        float yMove = Input.GetAxis("Vertical");
    
        float xSpeed = xMove * speed;
        float ySpeed = yMove * speed;
    
        Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
    
        rigidBody2D.velocity = newVelocity;	
    
        // restrict player movement
        KeepWithinMinMaxRectangle();
      }
  7. With the player-SpaceGirl1 GameObject in the Hierarchy view, drag the corner_max and corner_min GameObjects over the public variables called corner_max and corner_min in the Inspector.
  8. Before running the scene in the Scene panel, try repositioning the corner_max and corner_min GameObjects. When you run the scene, the positions of these two GameObjects (max and min, and X and Y) will be used as the limits of movement for the Player's player-SpaceGirl1 character.
  9. While all this works fine, let's make the rectangular bounds of the movement visually explicit in the Scene panel by having a yellow "gizmo" rectangle drawn. Add the following method to the C# script class called PlayerMove:
    void OnDrawGizmos(){
      Vector3 top_right = Vector3.zero;
      Vector3 bottom_right = Vector3.zero;
      Vector3 bottom_left = Vector3.zero;
      Vector3 top_left = Vector3.zero;
    
      if(corner_max && corner_min){
        top_right = corner_max.position;
        bottom_left = corner_min.position;
    
        bottom_right = top_right;
        bottom_right.y = bottom_left.y;
    
        top_left = top_right;
        top_left.x = bottom_left.x;
      }
    
      //Set the following gizmo colors to YELLOW
      Gizmos.color = Color.yellow;
    
      //Draw 4 lines making a rectangle
      Gizmos.DrawLine(top_right, bottom_right);
      Gizmos.DrawLine(bottom_right, bottom_left);
      Gizmos.DrawLine(bottom_left, top_left);
      Gizmos.DrawLine(top_left, top_right);
    }

How it works...

You added the empty GameObjects called corner_max and corner_min to the scene. The X- and Y- coordinates of these GameObjects will be used to determine the bounds of movement that we will permit for the character called player-SpaceGirl1. Since these are the empty GameObjects, they will not be seen by the player when in the play-mode. However, we can see and move them in the Scene panel, and having added the yellow oblong icons, we can see their positions and names very easily.

Upon Awake() the PlayerMoveWithLimits object, inside the player-SpaceGirl1 GameObject, records the maximum and minimum X- and Y- values of the GameObjects called corner_max and corner_min. Each time the physics system is called via the FixedUpdate() method, the velocity of the player-SpaceGirl1 character is set according to the horizontal and vertical keyboard/joystick inputs. However, the final action of the FixedUpdate() method is to call the KeepWithinMinMaxRectangle() method, which uses the Math.Clamp(…) function to move the character back inside the X- and Y- limits. This happens so that the player's character is not permitted to move outside the area defined by the corner_max and corner_min GameObjects.

The OnDrawGizmos() method tests that the references to the corner_max and corner_min GameObjects are not null, and then sets the positions of the four Vector3 objects, representing the four corners defined by the rectangle with corner_max and corner_min at the opposite corners. It then sets the Gizmo color to yellow, and draws lines, connecting the four corners in the Scene panel.

See also

Refer to the next recipe for more information about limiting player controlled character movements.

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

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