As the title says, im working on a unity2d platformer for my first year uni assignment, and for some reason my character can jump constantly when in the air, i cant figure out why though. Not sure if its a scripting issue or something related to the characters child “groundcheck”. any help would be sincearly appreciated. Also if this isnt the right thread could someone direct me to the correct place please aha.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float horizontal;
private float speed = 5f;
private float jumpingPower = 15f;
private bool isFacingRight = true;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
void Update()
//determining if player is grounded for the jumping mechanic
{
horizontal = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
//determining jump velocity
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
//Controlling the jumping mechanic
//Adding force vertically
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpingPower, ForceMode2D.Impulse);
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
//Flip mechanic
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
8632512–1160610–PlayerMovement.cs (1.74 KB)