so im working on jumping for my game, and for some reason when i press space at the right velocity while it’s falling, the player jumps higher than what it’s supposed to jump, can somebody tell me how and why?
here’s the code
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
#region Variables
#region Movement
[Header("Movement")]
public float acceleration;
public float maxSpeed;
public float deceleration; // will be used later
#endregion
#region Components
[Header("Components")]
Rigidbody2D rb;
BoxCollider2D coll;
#endregion
#region Jump
[Header("Jump")]
public float jumpHeight;
#endregion
#region Gravity
[Header("Gravity")]
public float gravityScale;
public float fallGravityScale;
#endregion
#region Collision
[Header("Collision")]
public Vector2 boxSize;
public float boxDistance;
public LayerMask groundLayer;
#endregion
#endregion
private void Awake() {
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
}
void Update() {
Movement();
Jump();
}
#region Movement Code
void Movement()
{
float horizontal = Input.GetAxis("Horizontal");
Vector2 direction = new(horizontal, 0);
rb.AddForce(acceleration * direction, ForceMode2D.Force);
if (rb.velocity.magnitude <= maxSpeed)
{
return;
}
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
}
void Jump(){
if(Input.GetKeyDown(KeyCode.Space) && IsGrounded()){
float jumpForce = Mathf.Sqrt(jumpHeight * (Physics2D.gravity.y * rb.gravityScale) * -2);
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
if(rb.velocity.y >= 0){
rb.gravityScale = gravityScale;
}
else{
rb.gravityScale = fallGravityScale;
}
}
#endregion
private bool IsGrounded(){
return Physics2D.BoxCast(transform.position,boxSize,0f,-transform.up,boxDistance,collisionLayer);
}
private void OnDrawGizmos() {
Gizmos.color = Color.green;
Gizmos.DrawWireCube(transform.position-transform.up*boxDistance,boxSize);
}
}