Search Unity

Help with creating invisible boundaries

Discussion in 'Getting Started' started by Iqew, Oct 29, 2017.

  1. Iqew

    Iqew

    Joined:
    Nov 26, 2016
    Posts:
    38
    I'm trying to make sure my player doesn't go out of the screen using code but for some reason only the upper and right part of the screen has boundaries. Here's my code and a screenshot highlighting the parts that have boundaries.
    boundaries.png

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour {
    6.  
    7.     public Vector2 speed;
    8.     private Rigidbody2D rb2d;
    9.     private float ScreenHalfSize;
    10.  
    11.     void Start () {
    12.         rb2d = GetComponent<Rigidbody2D> ();
    13.         ScreenHalfSize = Camera.main.aspect * Camera.main.orthographicSize;
    14.     }
    15.  
    16.     void FixedUpdate () {
    17.         Vector2 velocity;
    18.         velocity.x = Input.GetAxis ("Horizontal") * speed.x * Time.deltaTime;
    19.         velocity.y = Input.GetAxis ("Vertical") * speed.y * Time.deltaTime;
    20.  
    21.         transform.Translate (velocity);
    22.  
    23.         if (transform.position.x <= -ScreenHalfSize) {
    24.             Debug.Log("x <= -ScreenHalfSize");
    25.             transform.Translate (new Vector2 (velocity.x, 0));
    26.         }
    27.         else if (transform.position.x >= ScreenHalfSize) {
    28.             Debug.Log("x >= ScreenHalfSize");
    29.             transform.Translate (new Vector2 (-velocity.x, 0));
    30.         }
    31.         if (transform.position.y <= -Camera.main.orthographicSize) {
    32.             Debug.Log("y <= -ScreenHalfSize");
    33.             transform.Translate (new Vector2 (0, velocity.y));
    34.         }
    35.         else if (transform.position.y >= Camera.main.orthographicSize) {
    36.             Debug.Log("y >= ScreenHalfSize");
    37.             transform.Translate (new Vector2 (0, -velocity.y));
    38.         }
    39.  
    40.     }
    41. }
     
  2. Iqew

    Iqew

    Joined:
    Nov 26, 2016
    Posts:
    38
    Please ignore this thread. I've already found a solution. I feel so stupid about using positive velocity.x/velocity.y in order to cancel the velocity.