I’m writing a 2D platformer and I’m looking to improve the physics on my character. So far it’s very simple. Current limitations include not being able to change direction while jumping. Also it just doesn’t feel as natural as I’d like. Is there some way I can implement Unity’s Physics to better define this character’s movements and behaviour?
The code for the character’s movement is below.
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
float rotation = Input.GetAxis("Horizontal");
if(controller.isGrounded)
{
moveDirection.Set(rotation, 0, 0); //moveDirection = new Vector3(rotation, 0, 0);
moveDirection = transform.TransformDirection(moveDirection);
//running code
if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) //check if shift is held
{ running = true; }
else
{ running = false; }
moveDirection *= running ? runningSpeed : walkingSpeed; //set speed
//jump code
if(Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpHeight;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}