Character sliding across terrain
I wrote a simple character movement script but for some reason when the character starts moving they slide slowly across the map. I'm not new to programming but I am new to C# so I'm unsure if there is something I am missing in my code. Any help would be greatly appreciated!
[SerializeField] private string horizontalInputName;
[SerializeField] private string verticalInputName;
[SerializeField] private float movementSpeed;
private bool isMoving = false;
private CharacterController chardController;
private void PlayerMovement(){
if (((Input.GetAxisRaw(horizontalInputName)) != 0) || ((Input.GetAxisRaw(verticalInputName)) != 0))
{
isMoving = true;
Debug.Log ("is moving");
}
else
{
isMoving = false;
Debug.Log ("is not moving");
}
if (isMoving)
{
float horizInput = Input.GetAxisRaw (horizontalInputName) * movementSpeed;
float vertInput = Input.GetAxisRaw (verticalInputName) * movementSpeed;
Vector3 forwardMovement = transform.forward * vertInput;
Vector3 rightMovement = transform.right * horizInput;
chardController.SimpleMove (forwardMovement + rightMovement);
}
else
{
chardController.gameObject.transform.position = Vector3.zero;
}
JumpInput ();
SprintInput ();
}
Answer by MakhairaGirl · Dec 06, 2020 at 03:12 PM
I figured out the solution for anyone who runs into this problem and has a character controller set up this way. For some reason when I use an Xbox controller instead of the keyboard it never sets the axis values to 0 so the statement:
if (((Input.GetAxisRaw(horizontalInputName)) != 0) |((Input.GetAxisRaw(verticalInputName)) != 0))
really should be:
if ((((Input.GetAxisRaw(horizontalInputName)) > 0.1) || ((Input.GetAxisRaw(horizontalInputName)) < -0.1)) || (((Input.GetAxisRaw(verticalInputName)) > 0.1) || ((Input.GetAxisRaw(verticalInputName)) < -0.1)))
Also, I did:
chardController.gameObject.transform.position = Vector3.zero; as a definitive way to test if my boolean worked but the correct line of code would be:
chardController.SimpleMove (new Vector3 (0, 0, 0)); so it doesn't set it back to the origin of the map.
Hope this helps!