Search Unity

Prevent a GameObject from leaving a particular region

Discussion in 'Scripting' started by Deleted User, Nov 29, 2015.

  1. Deleted User

    Deleted User

    Guest

    I'm trying to prevent a GameObject from leaving a particular region. Now the hard part is that the region doesn't have to be rectangular shaped so what I've been doing so far--clamping the x & y values of the GameObject's destination to the min/max bounds of the shape--will not work. I need a to find a way to constrain the GameObject to the shape defined in the class. The GameObject is also a kinematic rigidbody so that make things a bit more difficult.

    This is some of the code I have so far (WIP):

    Code (CSharp):
    1. public class Prisoner2D : Component
    2.     {
    3.         [SerializeField] private Movement _movement;
    4.         [SerializeField] private Collider2D _prison;
    5.  
    6.         private Bounds _bounds;
    7.  
    8.         private void Start()
    9.         {
    10.             _movement.OnStarted.AddListener(MoveTo);
    11.             if (_prison != null)
    12.             {
    13.                 _bounds = _prison.bounds;
    14.             }
    15.         }
    16.  
    17.         public void SetPrison(Collider2D prison)
    18.         {
    19.             _prison = prison;
    20.             _bounds = prison.bounds;
    21.         }
    22.  
    23.         public void MoveTo(Vector2 position)
    24.         {
    25.             Vector2 min;
    26.             Vector2 max;
    27.  
    28.             if (!_prison.gameObject.isStatic)
    29.             {
    30.                 var bounds = _prison.bounds;
    31.                 min = bounds.min;
    32.                 max = bounds.max;
    33.             }
    34.             else
    35.             {
    36.                 min = _bounds.min;
    37.                 max = _bounds.max;
    38.             }
    39.  
    40.             float x = Mathf.Clamp(position.x, min.x, max.x);
    41.             float y = Mathf.Clamp(position.y, min.y, max.y);
    42.             var destination = new Vector2(x, y);
    43.             _movement.MoveTo(destination);
    44.         }
    45.  
    46.         public void MoveTo(Vector3 position)
    47.         {
    48.             Vector2 position2D = position;
    49.             MoveTo(position2D);
    50.         }
    51.     }
     
  2. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389