- Home /
Inconsistent jump height
So I am working on a 2D platformer game on Android. At the start, my character jumps normally but whenever the score reaches about to 20 (the score is based on time) my character seems to be jumping higher that it should.
I've searched some solutions such as using Mathf.Clamp
but it still doesn't work. I've already added a boolean variable for being grounded but still, it isn't working.
Here's my code. I'm using Standard Assets as I've watched on a short YouTube video.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Control : MonoBehaviour
{
//movement
rb = GetComponent<Rigidbody2D>();
public void Update()
{
if (grounded)
{
rb.velocity = Vector3.zero;
rb.angularVelocity = 0f;
}
if (CrossPlatformInputManager.GetButtonDown("Jump") && grounded)
{
rb.AddForce(Vector2.up * 600f);
}
}
public void OnTriggerStay2D(Collider2D col)
{
if (col.gameObject.tag.Equals("tall box") || col.gameObject.tag.Equals("short box") || col.gameObject.tag.Equals("small box") || col.gameObject.tag.Equals("platform"))
grounded = true;
}
public void OnTriggerExit2D(Collider2D col)
{
grounded = false;
}
}
I've also tried to add the Mathf.Clamp
and added it in the Update
but it still doesn't work.
Here's the code
rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -4f, 4f));
I would really appreciate if this gets answered, this is my first ever project in unity and I'm hoping that it would turn out well.
Answer by sztobar · Oct 10, 2020 at 09:17 PM
I think that rb.AddForce(Vector2.up * 600f);
might be called multiple times. You can do a simple check by adding Debug.Log("Control jump");
in the next line and see how many times it gets logged after pressing the jump button only once.
It may happen becuase you're using trigger
collision to detect if object is grounded or not. If this collider is big enough it may still overlap something after object jumps. Becuase of that when you click "jump" button rb.AddForce(Vector2.up * 600f);
may be called even 6 times.