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

Question Limit player movement on X and Z

Discussion in 'Scripting' started by cydium, Mar 23, 2023.

  1. cydium

    cydium

    Joined:
    Jan 7, 2022
    Posts:
    2
    How can I set the x and z limits of the player? Like between -10 and 10 for X. -5 and 5 for Z.

    Code (CSharp):
    1. moveVector = Vector3.zero;
    2. moveVector.x = floatingJoystick.Horizontal * moveSpeed;
    3. moveVector.z = floatingJoystick.Vertical * moveSpeed;
    4.  
    5. if (Vector3.Angle(Vector3.forward, moveVector) > 1f || Vector3.Angle(Vector3.forward, moveVector) == 0)
    6. {
    7.     ch_controller.Move(moveVector * Time.deltaTime);
    8. }
     
  2. samana1407

    samana1407

    Joined:
    Aug 23, 2015
    Posts:
    76
    You can use if statement.
    Code (CSharp):
    1. if( moveVector.z < -5)
    2.      moveVector.z = -5;
    and so forth.
    But most easyest way to use Mathf.Clamp in this case

    Code (CSharp):
    1. moveVector.x = Mathf.Clamp( moveVector.x, -10, 10);
    2. moveVector.z = Mathf.Clamp( moveVector.z, -5, 5);
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    :)

    I was gonna suggest that too @samana1407 ... but look again:

    movement
    is actually the delta, not the position.

    I don't actually know the solution off the top of my head for plucking a position out of a CC, updating it, and putting it back.
     
    samana1407 likes this.
  4. samana1407

    samana1407

    Joined:
    Aug 23, 2015
    Posts:
    76
    But really!! Thank you!
     
  5. cydium

    cydium

    Joined:
    Jan 7, 2022
    Posts:
    2
    Thanks!