Search Unity

Mathf.Clamp not taking effect

Discussion in 'Scripting' started by Ragee, Jun 8, 2020.

  1. Ragee

    Ragee

    Joined:
    Nov 24, 2012
    Posts:
    15
    I have a very simple script written to allow player to wrap around the screen on the X axis when Q is held down but Y should always be clamped.

    What I cannot get my head around is how in the below code Y is not getting clamped while Q is held down.
    Y is however getting clamped properly if Q is not held down.

    Code (CSharp):
    1. //Move player based on axis input
    2.         transform.Translate(new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * Time.deltaTime * speed);
    3.  
    4.         //If Q is held down allow horizontal wrapping
    5.         if (Input.GetKey(KeyCode.Q) && transform.position.x < -11.2f)
    6.         {
    7.             transform.position = new Vector3(11.2f, Mathf.Clamp(transform.position.y, -3.8f, 0), 0);
    8.         }
    9.         else if (Input.GetKey(KeyCode.Q) && transform.position.x > 11.2f)
    10.         {
    11.          
    12.             transform.position = new Vector3(-11.2f, Mathf.Clamp(transform.position.y, -3.8f, 0), 0);
    13.         }
    14.  
    15.         if(!Input.GetKey(KeyCode.Q) && transform.position.x > -11.2f & transform.position.x < 11.2f)
    16.             transform.position = new Vector3(Mathf.Clamp(transform.position.x, -9f, 9f), Mathf.Clamp(transform.position.y, -3.8f, 0), 0);
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,913
    You code will only clamp y if transform.position.x < -11.2f or transform.position.x > 11.2f because you are AND-ing those conditions to the first set of if/else statements. Overasll your logic here is very convoluted. I suggest simplifying the whole thing:

    Code (CSharp):
    1. //Move player based on axis input
    2. Vector3 newPosition = transform.position + new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * Time.deltaTime * speed);
    3.  
    4. // always clamp y:
    5. newPosition.y = Mathf.Clamp(newPosition.y, -3.8f, 0f);
    6. // Always set z to 0
    7. newPosition.z = 0;
    8.  
    9. // Wrap X if Q is held down:
    10. bool wrapX = Input.GetKey(KeyCode.Q);
    11. if (wrapX) {
    12.   if (newPosition.x < -11.2f) {
    13.     newPosition.x = 11.2f;
    14.   }
    15.   else if (newPosition.x > 11.2f) {
    16.     newPosition.x = -11.2f;
    17.   }
    18. }
    19. // If Q is not held down, clamp X between -9 and 9
    20. else {
    21.   newPosition.x = Mathf.Clamp(newPosition.x, -9f, 9f);
    22. }
    23.  
    24. transform.position = newPosition;
    25.  
     
    Last edited: Jun 8, 2020
    Ragee likes this.
  3. Ragee

    Ragee

    Joined:
    Nov 24, 2012
    Posts:
    15
    Ahh yes of course, what an idiot I am.

    Thank you!