Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Implementing boundaries

Discussion in 'General Discussion' started by boolfone, Feb 4, 2015.

  1. boolfone

    boolfone

    Joined:
    Oct 2, 2014
    Posts:
    289
    I’m working on a game similar to Pong:



    I’m trying to figure out how to constrain the paddle so it can’t leave the viewing frustum. I’m hoping to make this work regardless of the screen dimensions. Anyone know how to do this?

    Thanks.
     
  2. randomperson42

    randomperson42

    Joined:
    Jun 29, 2013
    Posts:
    974
  3. boolfone

    boolfone

    Joined:
    Oct 2, 2014
    Posts:
    289
    Thanks. I think I got it working.

    Here's most of the code:

    Code (CSharp):
    1.         void Update ()
    2.         {
    3.                 float dx = Input.GetAxis ("Horizontal");
    4.                 transform.Translate (dx, 0, 0);
    5.  
    6.                 Vector3 left = camera.WorldToScreenPoint (this.collider.bounds.min);
    7.  
    8.                 if (left.x < 0) {
    9.                         // paddle went too far left, needs correction
    10.                         left.x = 0;
    11.                         Vector3 worldPoint = camera.ScreenToWorldPoint (left);
    12.                         transform.position = worldPoint + collider.bounds.extents;
    13.  
    14.                 }
    15.  
    16.  
    17.  
    18.                 Vector3 upperRightVertex = new Vector3 (collider.bounds.max.x, collider.bounds.min.y, collider.bounds.min.z);
    19.  
    20.                 Vector3 right = camera.WorldToScreenPoint (upperRightVertex);
    21.  
    22.                 if (right.x > Screen.width) {
    23.                         // paddle went too far right, needs correction
    24.                         right.x = Screen.width;
    25.                         Vector3 worldPoint = camera.ScreenToWorldPoint (right);
    26.                         transform.position = worldPoint + new Vector3 (-collider.bounds.extents.x,
    27.                                                            collider.bounds.extents.y,
    28.                                                            collider.bounds.extents.z);
    29.  
    30.  
    31.                 }
    32.  
    33.         }