I have my player using character controller or rigidbody…
if(Input.getbuttondown(keycode.Leftarrow))
{
movedirection.x=speed*Time.deltatime;
//
in there my player at x=0:now i have to move my player at x=1 when once left arrow is pressed…if again left arrow is pressed +1:someone help with this
//
}
As TreyH said, MathF.Clamp() would be used to limit the motion so it doesn’t go beyond a set range. You may still need this if you need to limit the player to specific boundaries.
Personally, I use Input.GetAxis(“Horizontal”) for movement, it’s a smoother result than with getbuttondown, unless you specifically want it to jump one step at a time. Here’s an example.
public gameObject MyObj;
float moveHorizontal;
float maxLeft = -15.0f;
float maxRight = 15.0f;
float moveSpeed = 0.5f;
void Update()
{
// Read the keyboard input ( - left and + right arrows or - A and + D keys)
moveHorizontal = Input.GetAxis("Horizontal");
// adjust the input for your scale and clamp it to your boundaries
moveHorizontal = Mathf.Clamp(moveHorizontal*moveSpeed*Time.deltatime,maxLeft,maxRight);
// apply the motion to your object
MyObj.transform.position = MyObj.transform.position+new Vector3(MoveHorizontal,0,0);
}
You can use GetButtonDown with leftarrow and also with rightarrow in place of GetAxis if you’d like. GetAxis does handle both directions with one command, however.
You can do the same thing with Input.GetAxis(“Vertical”) for up and down if you want, and that would go in place of the second 0 in the Vector3.
Or if you’re doing 2 dimensions, you’d probably be using a Vector2(x , y) without the third 0 for z.
Hope this helps.
Thanks for that…but still i cant understand how to use mathf.clamp with my player…
i used mathf.clamp with my player…but the code not working…can you give me some code !!……………thanks