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

Clamp not working

Discussion in 'Scripting' started by ellenblomw, May 25, 2019.

  1. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    Hi guys,

    I have a rigidbody2D attached to a gameobject that should stay inside certain boundaries. But it keeps falling of screen. Anyone know why my clamp isn't working? Script is attached to the gameobject and I can see by debugging that the x and y position far exceds my clamp limit.

    Code (CSharp):
    1. {
    2.     private Vector2 pos;
    3.  
    4.     void Start ()
    5.     {
    6.         pos = transform.position;
    7.     }
    8.  
    9.     void FixedUpdate () {
    10.         pos.x = Mathf.Clamp(pos.x, 440.38f, 447.72f);
    11.         pos.y = Mathf.Clamp(pos.y, 161.25f, 165.03f);
    12.         Debug.Log(transform.position);
    13.     }
    14. }
    15.  
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,754
    Yor pos is just a copied vector2 not a reference of transform position.
    So you need assign your pos to transform.position.
     
    ellenblomw likes this.
  3. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    Sorry, never mind, forgot to assign the position to the pos :p
     
    Antypodish likes this.
  4. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    Thanks Anty, yeah, how stupid of me lol, just figured!