# Mathf.Clamp explaination

Hio! I’m rather new to game programming and I’m not sure if I understand Mathf.Clamp correctly. I’m currently working on a VERY basic FPS game and when I walk forward/backwards or right/left my speed is limited to 5. However when I press W and D at the same time (moving in a 45 degree kind of line) my speed becomes close to doubled. I try to solve this by doing:

1. create a variable containing both forwardSpeed and sideSpeed.

2. clamp the variable to -movementSpeed, movementSpeed.

But nothing happens. Am I far out sailing? I’d appreciate an explaination on what I’m doing wrong rather than just a coded answer (or both). Here is the important code so far (not the clamped one).

``````public float movementSpeed = 5.0f; // The movement speed my player will move in

void Update () {
float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
``````

Actually a clamp isn’t going to help you if you just add the values on to the position, because your code is adding it twice when it touches the x and z positions.

You would probably be better off using a Vector:

``````var move = new Vector3(sideSpeed, 0, forwardSpeed);
``````

Now you have a vector whose size can be your double speed, so we need to clamp it’s size but maintain its direction.

`````` var moveAmount = Mathf.Clamp(move.magnitude, 0, maxSpeed);
``````

And size the vector to that magnitude

``````  move = move.normalized * moveAmount;

transform.localPosition += move;
``````