mathf.clamp is not working

i wrote a script for clamping the xvalues but when i run the script the clamp is ignored. can anyone explain why.

using UnityEngine;
using System.Collections;

public class player_movement : MonoBehaviour {

    public float speed = 2; 
	private float xLeftLimit = -1.642209f;
	private float xRightLimit = 1.626122f;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	float amtToMoveXdir = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
	float amtToMoveXdirClamp = Mathf.Clamp(amtToMoveXdir, xLeftLimit, xRightLimit);
	transform.Translate(Vector3.right * amtToMoveXdirClamp);
	
	float amtToMoveZdir = Input.GetAxis("Vertical") * speed * Time.deltaTime;
	transform.Translate(Vector3.forward * amtToMoveZdir);
	
	//float XmovementClamp = Mathf.Clamp(amtToMoveXdir, xLeftLimit, xRightLimit);
	
	}
}

i think it should work, check the clamp rang higher

no it is moving out of the range.

thanks moor and alucardj for the help.

2 Answers

2

Try adding a Debug.log(amtToMoveXdirClamp); and see what’s the value after the clamp.

The Clamp is working, you are never reaching the min and max clamp values. For example :

axis * speed * deltaTime is approximately
1.0 * 2 * 0.02 = 0.04

No way will amtToMoveXdir ever be above or below 1 or -1, let alone 1.6

You can check this as advised by @Moor with a Debug :

Debug.Log( "amtToMoveXdir = " + amtToMoveXdir  + " : amtToMoveXdirClamp = " + amtToMoveXdirClamp );

Add this line after your calculations (line 20)