I am having this problem where the player jumps 2x-3x as high as he should if he jumps of a platform/Ground edge. I am not sure why he does that. Here is the code.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header(“Moving”)]
[SerializeField] private float moveSpeed;
[Header("Jumping")]
[SerializeField] private KeyCode jumpKey = KeyCode.Space;
[SerializeField] private float jumpHeight;
[Header("Gravity Scales")]
[SerializeField] private float normalGravityScale;
[SerializeField] private float fallGravityScale;
[Header("Ground Check")]
[SerializeField] private LayerMask groundLayer;
[SerializeField] private Transform groundCheck;
[SerializeField] private float raySize;
private float horizontalInput;
private Rigidbody2D rb;
private bool isFacingRight = true;
[Header("Cayote Time")]
[SerializeField] private float cayoteTime;
private float cayoteTimeCounter;
private void Start()
{
Cursor.visible = false;
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
if (horizontalInput < 0 && !isFacingRight || horizontalInput > 0 && isFacingRight)
{
Flip();
}
if (rb.velocity.y >= 0)
{
rb.gravityScale = normalGravityScale;
}
else if (rb.velocity.y <= 0)
{
rb.gravityScale = fallGravityScale;
}
if (isGrounded()){
cayoteTimeCounter = cayoteTime;
}else{
cayoteTimeCounter -= Time.deltaTime;
}
}
private void FixedUpdate()
{
MovePlayer();
if (Input.GetKeyDown(jumpKey) && cayoteTimeCounter > 0f)
{
Jump();
}
}
private void MovePlayer()
{
rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
}
private void Jump()
{
float jumpForce = Mathf.Sqrt(jumpHeight * -2 * (Physics2D.gravity.y * rb.gravityScale));
rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
private void Flip()
{
Vector3 currentScale = gameObject.transform.localScale;
currentScale.x *= -1;
gameObject.transform.localScale = currentScale;
isFacingRight = !isFacingRight;
}
private bool isGrounded()
{
Vector2 rayPos = groundCheck.position;
Vector2 rayDir = Vector2.down;
RaycastHit2D hit = Physics2D.Raycast(rayPos, rayDir, raySize, groundLayer);
if (hit.collider != null){
return true;
}
return false;
}
}