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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Stop the player when striking the edge of the screen

Discussion in 'Scripting' started by Miles313, Oct 15, 2015.

  1. Miles313

    Miles313

    Joined:
    Oct 15, 2015
    Posts:
    3
    Hi guys!

    I'm having a little trouble to make the player stop when attain being the display limit. I used the code:
    Code (csharp):
    1. if (transform.position.y > 14)
    2.             transform.position = new Vector3 (transform.position.y, 14);
    But when the player touches the edge of the screen it moves it to as it should, but teleports 10 x too, what is the reason?

    thx!
     
  2. Duugu

    Duugu

    Joined:
    May 23, 2015
    Posts:
    241
    The parameters of Vector3() are x, y or x, y, and z.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Using physics? Just put up an invisible collider
     
    Lethn likes this.
  4. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    Code (CSharp):
    1. Vector3 pos = transform.position;
    2. if (pos.y > 14f) {
    3.     pos.y = 14f;
    4.     transform.position = pos;
    5. }
     
    Miles313 likes this.
  5. Miles313

    Miles313

    Joined:
    Oct 15, 2015
    Posts:
    3
    I'm not using psychic or rigidbody and thanks Ben, work!
    But, i added more line to catch the bottom edge too, like this:
    Code (CSharp):
    1. Vector3 pos = transform.position;
    2.         if (pos.y > 14f)
    3.         {
    4.             pos.y = 14f;
    5.             transform.position = pos;
    6.         }
    7.         if (pos.y > -15f)
    8.         {
    9.             pos.y = -15f;
    10.             transform.position = pos;
    11.         }
    But when I start the game, the player teleport y -14. I've removed the pos 14 and only left the -15, but this only occurs when a negative value is added. I'm looking for the causes. Thx!
     
  6. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    Is your player parented to something?
     
  7. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    The > -15 should probably be < -15
     
    Miles313 and BenZed like this.
  8. Miles313

    Miles313

    Joined:
    Oct 15, 2015
    Posts:
    3
    No.

    Oh... is really this, thank you XD