I wanted to implement a Roll function, where my character gets a little boost while rolling. It works totally fine while standing still, but while im moving left or right, most of the times the character wouldnt roll even though the input gets recognised. What could be the problem?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator animator;
public float groundSpeed;
public float jumpHeight;
[Range(0f, 1f)]
public float groundDecay;
public bool grounded;
public bool jumpUp;
public bool jumpDown;
public Rigidbody2D body;
public BoxCollider2D groundCheck;
public SpriteRenderer sprite;
public LayerMask groundMask;
public float xInput;
public bool yInput;
public float rollSpeed;
void Start()
{
}
// Update is called once per frame
void Update()
{
GetInput();
MoveWithInput();
JumpCheck();
Rolling();
}
void FixedUpdate()
{
CheckGround();
ApplyFriction();
PlayerDirection();
Standing();
}
void GetInput()
{
xInput = Input.GetAxis("Horizontal");
yInput = Input.GetButtonDown("Jump");
}
void MoveWithInput()
{
if (Mathf.Abs(xInput) > 0)
{
body.linearVelocity = new Vector2(xInput * groundSpeed, body.linearVelocity.y);
animator.SetBool("running", true);
}
if (yInput && grounded)
{
body.linearVelocity = new Vector2(body.linearVelocity.x, jumpHeight);
}
}
void CheckGround()
{
grounded = Physics2D.OverlapAreaAll(groundCheck.bounds.min, groundCheck.bounds.max, groundMask).Length > 0;
if (grounded)
{
animator.SetBool("jumpdown", false);
animator.SetBool("jump", false);
}
}
void ApplyFriction()
{
if (grounded && xInput == 0 && !yInput)
{
body.linearVelocity = new Vector2(body.linearVelocity.x * groundDecay, body.linearVelocity.y);
}
}
void JumpCheck()
{
if (body.linearVelocity.y > 0 && !grounded)
{
animator.SetBool("jump", true);
}
if (body.linearVelocity.y < 0 && !grounded)
{
animator.SetBool("jumpdown", true);
animator.SetBool("jump", false);
}
}
void PlayerDirection()
{
if (xInput < 0)
{
sprite.flipX = true;
}
if (xInput > 0)
{
sprite.flipX = false;
}
}
void Standing()
{
if (body.linearVelocity.x <= 0.1 || !grounded)
{
animator.SetBool("running", false);
}
}
void Rolling()
{
if (Input.GetKeyDown(KeyCode.LeftShift) && grounded)
{
Vector2 rollDirection = sprite.flipX ? Vector2.left : Vector2.right;
body.AddForce(rollDirection * rollSpeed + body.linearVelocity, ForceMode2D.Impulse);
animator.SetTrigger("roll");
Debug.Log("Rolling while running in direction: " + rollDirection);
}
}
}