I have a Cube(Player) in my game scene. I have written a C# script to constrain the movement(using Mathf.Clamp()
) of the Cube so it does not leave the screen.
Below is my FixedUpdate()
method from the Script
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.velocity = movement * speed;
rb.position = new Vector3(
Mathf.Clamp (rb.position.x, x_min, x_max),
0.5f,
Mathf.Clamp(rb.position.z, z_min, z_max)
);
}
Values of x_min
, x_max
, z_min
, z_max
are -3, 3, -2, 8 respectively inputted via the unity inspector.
PROBLEM
The script is working fine but my player(Cube) can move up to -3.1 units in negative X-AXIS
(if I keep pressing the left arrow button) which is 0.1 units more in negative X-AXIS
(This behavior is true for other axes too). It obviously clamps -3.1 to -3 when I stop pressing the button.
- Why is this happening? Why doesn't it(
Mathf.Clamp()
) restrict the Cube to -3 units in first place? - Why am I getting that extra 0.1 units?
- And Why is this value 0.1 units only? Why not more or less?