unity 3d student

Beginner B26 – Using Mathf.Clamp to restrict values

Using Mathf.Clamp function to restrict values in your game mechanics to within a specified range.

Code Used (Javascript)

function Update () {
  1.  var xMove : float = Input.GetAxis("Horizontal") * Time.deltaTime * 20;
  2.  transform.Translate(Vector3(xMove,0,0));
  3.  transform.position.x = Mathf.Clamp(transform.position.x, -10, 10);
  4. }

Further Reading

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

30 Comments

    This looks like a simple and great way to limit both the player and objects interacting with each other in a side-scrolling type of game. Thanks for the tutorial! 🙂

    • Thanks for the comment Ragnarock, there are plenty of uses of Clamp, from animation to screen restriction right down to very simple script elements, perhaps restricting randomisation for example. Happy Devving!

    You’r doing a great work.
    congrats 🙂

  • Отличные уроки для новичков, спасибо )
    Great lessons for beginners, thx )

  • Good stuff, but the “Next” button links to C01 instead of B27. Thought you should know 🙂

    Pe-ads

  • Does this function also work if you use it on things such as a timer or an ammunition value?

    • Certainly, all it does it limit floating point (decimal placed) number values to what you specify, so there are a myriad of explanations.

    Hi great site! I decided to take challenge 3 and step it up a bit. Making a small rotating cannon in a fixed location. However I noticed that whenever I rotate the turret in the X axis it sticks at 90 degrees. Why is this?

  • Just to add to the above, the sticking has nothing to do with the limiting that is going on in the script. It seems that I just cannot rotate any object via script past 90 degrees on the X axis.

  • Hello !

    Thank you for the tutorial. However, what should I do if I want to restrict my object’s movement within the screen’s left and right border instead of fixed coordinates ?

  • I think this MathF.Clamp is really useful for Lerp Intervals 😉

  • 감사합니다

  • These tutorials are totally amazing. Thank you for such a well put together set of tut’s.

    I’ve come from using various sdk’s in the past the last being UDK and I’ll be honest in the fact that scripting has always been beyond my programming skills.

    That is, until I started watching these and going through them on my own afterwards. Everything is very clear and concise and leaves me with something to refer back to later on.

    I can’t believe this website isn’t flooded with comments of thanks tbh.

    Keep up the good work Will and Thank you again 😉

    • Cheers Tyborg, good luck with your development. Scripting is something that makes more sense the more you try out different solutions to problems. What helps me is making small prototypes of ideas and finding solutions / asking for help with them, you’ll learn a lot that way.

    Hola como estas?, yo lo hice en C# de esta manera:

    update(){
    x = Input.GetAxis(“Horizontal”) * speed * Time.deltaTime;
    transform.Translate(x, 0, 0);
    Vector3 pos = transform.position;
    pos.x=Mathf.Clamp(transform.position.x, 63.04f, 94.42f);
    transform.position = pos;
    }

    // funciona – it works //

  • transform.position.x = Mathf.Clamp(transform.position.x, -10, 10);

    doing that on c# doesnt work, this is the solution i found:

    transform.position = new Vector3(Mathf.Clamp(transform.position.x, -4, 4), transform.position.y, transform.position.z);

    • thx!

    Nice script, thoug anyone have an idea i tried the code but the on the player to restrict the same way as this and on the camera so that i dont see the edge of the screen, regardless of the camera script, the player seems to shake when im on the edges with the camera restriction script off. the way my character moves is exactly the same code as this so?

  • Nice script, though anyone have an idea i tried the code but the on the player to restrict the same way as this and on the camera so that i dont see the edge of the screen, regardless of the camera script, the player seems to shake when im on the edges with the camera restriction script off. the way my character moves is exactly the same code as this so?

  • I see Erick above has a C# version. This is a question to both of you as I’m not sure if Erick was having the same issue. When using Mathf.Clamp in a C# script it ‘bounces’ at the boundaries of the values specified. For instance, if I have the ‘y’ value clamped to 4.0, it ‘bounces’ beyond 4 (ex. 4.08-4.02-4.05, etc.) But when using it with a Javascript it does not go beyond the desired value.

    Any ideas how to make this not ‘bounce’ with a C# script?

    Thanks in advance!
    -Chip

  • HI, i tryed to change this to work in the Y axis but i keep geting the “can not add float to.” error

    #pragma strict

    function Update () {

    var yMove ; float = Input.GetAxis(“Vertical”) * Time.deltaTime * 20;

    transform.Translate(Vector3(0,yMove,0));

    transform.position.y = Mathf.Clamp(transform.position.y,10,10);
    }

    plz help…

  • Love this one! I never really learned how to use MathF.Clamp before or what it was for. This explains it perfectly and is so easy to understand. Thank you Will.

  • Hello! I am using Unity 4.0. I tried this small lesson without clamping the movement but the cube I am attaching the script to, is not moving at all. I did everything just the same as you showed in this lesson but I cannot get the cube to be moved. Does any of you guys have an idea of what could be missing? Is because of the version of Unit I am using -which seems to be a most recent version than the used in the examples and lessons.

    Thanks in advance and let me congratulate you for your webpage and for having taken the time to do this. It is really very useful and amazingly easy to follow!

    Cheers!

    Armando.

  • C# code

    using UnityEngine;
    using System.Collections;

    public class MoveObjectC : MonoBehaviour {

    void Start ()
    {

    }

    void Update ()
    {
    float xMove = Input.GetAxis(“Horizontal”) * Time.deltaTime * 20;
    transform.Translate(xMove,0,0);

    transform.position = new Vector3(Mathf.Clamp(transform.position.x, -20, 20),3,0);
    }

    }

  • Cant we use a if statement to prevent it from moving past a certain point?

  • thankyou

  • Nice tutorial great work dude..

  • It’s great to find an expert who can exilpan things so well

  • thank u very much 😀 u help me ^_^

  • Great script, simple and clean.

Leave a Comment