when the player is jumping it can’t move left and right it can when it is falling.
this is the code:
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private float groundRayCastLength;
private bool onGround;
[SerializeField] private float acceleration;
[SerializeField] private float linearDrag;
[SerializeField] private float maxSpeed = 15;
[SerializeField] private float jumpForce = 12f;
[SerializeField] private float airLinearDrag = 2.5f;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private bool canJump => Input.GetButtonDown("Jump") && onGround;
private bool changingDirection => (rb.velocity.x > 0f && movement < 0f) || (rb.velocity.x < 0f && movement > 0f);
private float movement;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (canJump)
{
Jump();
}
}
private void checkCollisions()
{
onGround = Physics2D.Raycast(transform.position, Vector2.down, groundRayCastLength, groundLayer);
}
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundRayCastLength);
}
private void Jump()
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
private void MoveCharacter()
{
rb.AddForce(new Vector2(movement,0f) * acceleration);
if(Mathf.Abs(rb.velocity.x) > maxSpeed)
{
rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x)* maxSpeed,rb.velocity.y);
}
}
private void ApplyLinearDrag()
{
if (Mathf.Abs(movement)< 0.4f || changingDirection)
{
rb.drag = linearDrag;
}
else
{
rb.drag = 0f;
}
}
private void ApplyAirLinearDrag()
{
rb.drag = airLinearDrag;
}
private void FixedUpdate()
{
//moving left and right
movement = Input.GetAxis("Horizontal");
if (Input.GetKey(KeyCode.Space) && isJumping)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
MoveCharacter();
checkCollisions();
//flipping the player
if (movement > 0)
{
transform.localScale = new Vector2(1, 1);
}
if (movement < 0)
{
transform.localScale = new Vector2(-1, 1);
}
if (onGround)
{
ApplyLinearDrag();
}
else
{
ApplyAirLinearDrag();
}
}
}