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

Stop at screen borders?

Discussion in '2D' started by Loaphs, Aug 4, 2019.

  1. Loaphs

    Loaphs

    Joined:
    Jan 25, 2019
    Posts:
    3
    I'm trying to make my player stop at the screen border in a 2D game, but I can't because I "Cannot modify the return value of "Component.transform" because it is not a variable.

    Code (CSharp):
    1. if (Input.GetKey("down"))
    2.         {
    3.             transform.position -= ymov * Time.deltaTime;
    4.             DirectionDown();
    5.             if (transform.position.y < -4)
    6.             {
    7.                 transform.position.y = -4;
    8.             }
    9.         }
    So I ended up trying to use a Vector3 to set the position, and it worked, except for the fact that the player moved to the center of the X-Axis because the Vector3 X value was set to 0. I tried putting in the transform.position.x as a value for the Vector3, but because it cannot reference a "Component.transform".

    Code (CSharp):
    1. public Vector3 vborder = new Vector3(transform.position.x, 4.5F, 0);
    What do I do?
     
  2. therocketman2018

    therocketman2018

    Joined:
    Apr 25, 2019
    Posts:
    46
  3. Loaphs

    Loaphs

    Joined:
    Jan 25, 2019
    Posts:
    3
    I managed to make a solution. Since you couldn't add a non-static variable to a static variable, (or something like that), I just created the Vector3 variables in the Update method to make the variable non-static.
     
  4. AndyTruman

    AndyTruman

    Joined:
    Aug 19, 2019
    Posts:
    13
    That's wonderful! Effective use of Vector3 variables - thanks for sharing!
     
  5. Adien22

    Adien22

    Joined:
    Aug 19, 2019
    Posts:
    44
    Could you not also just use edge colliders at the borders? or is that more work?
     
  6. koolaid30995545

    koolaid30995545

    Joined:
    Jan 19, 2021
    Posts:
    1
    ive heard that this can cause issues later on in development, and is generally kinda "hackjob". but im not absolutely sure why to be honest (pretty new to this)