Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Boundary

Discussion in 'Scripting' started by Deleted User, Feb 27, 2021.

  1. Deleted User

    Deleted User

    Guest

    I have this script for a boundary, where my object can't move out of the boundary but it's not really working, Could I get some assistance?
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class LeftAndRight : MonoBehaviour
    4. {
    5.     public float speed = 1f;
    6.     public int x;
    7.     public float maxBound = 7;
    8.     public float minBound = -7;
    9.  
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.         if (Input.GetKey(KeyCode.D))
    14.         {
    15.             transform.Translate(Vector3.right * Time.deltaTime * speed);
    16.         }
    17.  
    18.         if (Input.GetKey(KeyCode.A))
    19.         {
    20.             transform.Translate(Vector3.left * Time.deltaTime * speed);
    21.         }
    22.     }
    23.  
    24.     void Boundary()
    25.     {
    26.         while((x > minBound))
    27.         {
    28.             if (Input.GetKey(KeyCode.D))
    29.             {
    30.                 transform.position = new Vector3(transform.position.x - 7, transform.position.y -7);
    31.             }
    32.         }
    33.         while((x > maxBound))
    34.         {
    35.             if (Input.GetKey(KeyCode.A))
    36.             {
    37.                 transform.position = new Vector3(transform.position.x -7, transform.position.y -7);
    38.             }
    39.         }
    40.     }
    41.  
    42.  
    43. }
    44.