In my jump system is something wrong, when i am clicking space button most of the times nothing happens butsomatimes it just teleport me up a bit .I was trying to do a smooth jump or just a simple jump that i can use every time i want .Do not help me in something like “Is Grounded”.Only thing i want is jump .Dow bellow is my code:
(ignore dashing and moving system, if you want to help me focus on a jumping system)
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
public class Player : MonoBehaviour
{
private Rigidbody2D rb;
public int movingSpeedX;
private float speedX;
public int jumpForce;
private bool canDash = true;
private bool isDashing = false;
public float DashingPower = 20;
public float dashingTime = 0.3f;
public float DashingCooldown = 1f;
public float gravityDeecreser = 2f;
private int keyCounterA = 0;
private int keyCounterD = 0;
[SerializeField] private TrailRenderer tr;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (keyCounterD > 2)
{
keyCounterD = 0;
}
else if (keyCounterD > 0)
{
Invoke(nameof(KeyReseterD), 0.3f);
}
if (keyCounterA > 2)
{
keyCounterA = 0;
}
else if (keyCounterA > 0) {
Invoke(nameof(KeyReseterA), 0.3f);
}
if (isDashing == true)
{
return;
}
speedX = Input.GetAxis("Horizontal") * movingSpeedX;
rb.velocity = new Vector2(speedX, 0);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
if (Input.GetKeyDown(KeyCode.A))
{
if (keyCounterA == 1&&canDash==true)
{
StartCoroutine(DashLeft());
keyCounterA = 0;
}
else
{
keyCounterA += 1;
}
}
if (Input.GetKeyDown(KeyCode.D))
{
if ( keyCounterD == 1 && canDash == true)
{
StartCoroutine(DashRight());
keyCounterD = 0;
}
else
{
keyCounterD += 1;
}
}
}
private IEnumerator DashRight() {
canDash = false;
isDashing = true;
float OrginalGravity = rb.gravityScale;
rb.gravityScale = gravityDeecreser;
rb.velocity = new Vector2(transform.localScale.x * DashingPower, 0f);
tr.emitting = true;
yield return new WaitForSeconds(dashingTime);
tr.emitting = false;
rb.gravityScale = OrginalGravity;
isDashing = false;
yield return new WaitForSeconds(DashingCooldown);
canDash = true;
}
private IEnumerator DashLeft()
{
canDash = false;
isDashing = true;
float OrginalGravity = rb.gravityScale;
rb.gravityScale = gravityDeecreser;
rb.velocity = new Vector2(transform.localScale.x * -DashingPower, 0f);
tr.emitting = true;
yield return new WaitForSeconds(dashingTime);
tr.emitting = false;
rb.gravityScale = OrginalGravity;
isDashing = false;
yield return new WaitForSeconds(DashingCooldown);
canDash = true;
}
private void KeyReseterD() {
keyCounterD = 0;
}
private void KeyReseterA()
{
keyCounterA = 0;
}
}