So i am fairly new to coding in C# and to unity and i am trying to practice by making a 2D platformer. However when implementing the jump my player climbs up infinitely i tried to use
gameObject.GetComponent<Rigidbody2D>().AddForce(Vector3.up * 1000);
once and i tried
rb.velocity= new vector2(rb.velocity.x, jumpforce)
once and it gave the very same result.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
Animator anim;
bool grounded;
public float speed;
public float jumpforce;
BoxCollider2D boxuwu;
public LayerMask groundLayer;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
boxuwu = GetComponent<BoxCollider2D>();
}
private void Update()
{
float hori = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(hori, rb.velocity.y) * speed;
if (hori > 0.01f)
{
transform.localScale = Vector3.one;
}
else if(hori < -0.01f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
anim.SetBool("Grounded", grounded);
if (Input.GetButtonDown("Jump") && isGrounded())
{
jump();
}
anim.SetBool("Running", hori != 0);
anim.SetBool("Grounded", isGrounded());
}
void jump()
{
gameObject.GetComponent<Rigidbody2D>().AddForce(Vector3.up * 1000);
anim.SetTrigger("Jump");
return;
}
private void OnCollisionEnter2D(Collision2D collision)
{
}
private bool isGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxuwu.bounds.center, boxuwu.bounds.size, 0, Vector2.down, 0.1f, groundLayer);
return raycastHit.collider != null;
}
}