Jumping works fine but i can jump mid air, even with this code … where is the flaw in my code? thank you in advance.
[SerializeField] float throttle = 6f; // pawn speed
[SerializeField] Rigidbody2D rb2d;
[SerializeField] float jmpfrc = 300f;
public bool isGrounded = true;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
//Debug.DrawRay(transform.position, new Vector2(0, -1), Color.red, .5f);
if (Input.GetAxis("Horizontal") > 0 || Input.GetAxis("Horizontal") < 0)
{
transform.position += transform.right * throttle * Time.deltaTime * Input.GetAxis("Horizontal");
}
// **** IF GROUNDED ***************************************************************
if (Physics2D.Raycast(transform.position, new Vector2(0, -1), .5f))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
// **** END IF GROUNDED ***********************************************************
// **** JUMP **********************************************************************
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
rb2d.AddForce(transform.up * jmpfrc);
isGrounded = false;
}
// **** END JUMP ********************************************************************
}
I could understand your code and can checkout why raycasting is not working. But since you said your main aim is to stop mid air jump, I would recommend using vertical velocity check instead of raycasting.
Something like this should work
// **** JUMP **********************************************************************
if (Input.GetKeyDown(KeyCode.Space) && rb2d.velocity.y == 0)
{
rb2d.AddForce(transform.up * jmpfrc);
}
// **** END JUMP ********************************************************************
also instead of calling physics functions in update, try to always call them in fixed update. Because update function depends on game performance on certain mobile which is measured in FPS so update depends on rendering FPS but fixed update will call after each 0.02 seconds (or whatever is set in physics settings in project settings). So a better modified form should be
[SerializeField] float throttle = 6f; // pawn speed
[SerializeField] Rigidbody2D rb2d;
[SerializeField] float jmpfrc = 300f;
public bool jump = false;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetAxis("Horizontal") > 0 || Input.GetAxis("Horizontal") < 0)
{
transform.position += transform.right * throttle * Time.deltaTime * Input.GetAxis("Horizontal");
}
// **** JUMP **********************************************************************
if (Input.GetKeyDown(KeyCode.Space) && rb2d.velocity.y == 0)
{
jump = true;
}
// **** END JUMP ********************************************************************
}
void FixedUpdate()
{
jump = false;
rb2d.AddForce(transform.up * jmpfrc);
}
thank you GameHourStudio for all your help!!!