Character movement not moving character to right or left.
Hello i have a question. I am trying to write my own character movement system.
The player can walk and jump.
The problem is when the player pushed the D or A or S button he moves forward ( he is supposed to move forwards after the W button is pressed or when when moving diagonaly).How can i repair this ?
This is my script.
public float walkSpeed = 10f; public Camera cameraPlayer;
private float mouseSensitivity = 2.0f;
public Vector2 LookRange = new Vector2(-60f, 60f);
float mouseX;
float mouseY;
CharacterController charController;
public float gravity = -12f;
public float jumpHeight = 1f;
float velocityY;
float currentSpeed;
public float turnSmoothTime = 0.2f;
float turnSmoothVelocity;
public float speedSmoothTime = 0.1f;
float speedSmoothVelocity;
private void Start()
{
charController = GetComponent<CharacterController>();
}
private void Update()
{
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical"));
Vector3 directionInput = input.normalized;
//transform.Translate(moveAmount);
transform.Rotate(0, mouseX, 0);
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
mouseY -= Input.GetAxis("Mouse Y") * mouseSensitivity;
mouseY = Mathf.Clamp(mouseY, LookRange.x, LookRange.y);
cameraPlayer.transform.localRotation = Quaternion.Euler(mouseY, 0, 0);
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
MoveThePlayer(directionInput);
}
void MoveThePlayer(Vector3 directionInput)
{
Vector3 velocity = directionInput * walkSpeed;
Vector3 moveAmount = velocity * Time.deltaTime;
moveAmount = transform.TransformDirection(moveAmount);
float targetSpeed = walkSpeed * directionInput.magnitude;
currentSpeed = Mathf.SmoothDamp(currentSpeed,targetSpeed,ref speedSmoothVelocity, GetModifiedSmoothTime(speedSmoothTime));
Vector3 velocityMovement = transform.forward * currentSpeed + Vector3.up * velocityY;
charController.Move(velocityMovement * Time.deltaTime);
velocityY += Time.deltaTime * gravity;
currentSpeed = new Vector3(charController.velocity.x,0, charController.velocity.z).magnitude;
if (charController.isGrounded)
{
velocityY = 0;
}
}
void Jump()
{
if (charController.isGrounded)
{
float jumpVelocity = Mathf.Sqrt(-2 * gravity * jumpHeight);
velocityY = jumpVelocity;
}
}
float GetModifiedSmoothTime(float smoothTime)
{
if (charController.isGrounded)
{
return smoothTime;
}
return smoothTime;
}`