- Home /
double jump works fine but not when falling from a ledge, how to fix it?
i am making a 2d platformer, and i can move my player left and right and also flip its face while doing so, then i added double jump function. it worked well but i have one issue. i want my character to double jump when it is on ground, and if it falls from a ledge then it still should have its double jump feature. i am putting my code below, and i hope if anyone can help me. thanks already.
below is my code
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovement : MonoBehaviour { public float speed; public float jumpForce; private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatisGround;
private int extraJumps;
public int extraJumpsValue;
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatisGround);
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if (facingRight == false && moveInput > 0)
{
Flip();
}
else if (facingRight == true && moveInput < 0)
{
Flip();
}
}
void Update()
{
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
}
else if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps == 0 && isGrounded == true)
{
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
@UnityTo$$anonymous$$ake$$anonymous$$oney ·hello sir, i am sorry to bother you once again. actually since the last time, i have made much progress, even added a fire function and a lot more. actually right now i am stuck with dash attack, and whatever i do, i cant seem to get dash attack working, i tried various youtube tutorials, but nothing seemed to work, you are aware of my game idea, as i shared the link to the project with you, the player is either facing right or left, but i want to make it dash, when i press a key, so it dashes in the last move direction(either left or right) but this feature cannot be spammed and a player has to wait for few secs to get it working again, meanwhile when dashing, is it possible to damage the opponents? you can view my entire scrip till now here, and i m sure you will be amazed and happy to see my progress this far. i know no one here, and i request you for your help. thank you already sir. https://drive.google.com/file/d/1u6RIynqyATuNVBqF6UIwUYibOstpuqw2/view
Answer by UnityToMakeMoney · Sep 29, 2020 at 05:50 PM
I believe your code is perfectly fine, but since you are falling there is some velocity pushing the character down. Therefore, it looks like the player isn't moving, but in fact, the player does move with very little velocity upward.
How to Fix This:
Method 1
rb.velocity = new Vector2(0f, 0f);//changes velocity to 0
rb.velocity = Vector2.up * jumpForce;//moves character with initial velocity 0
Method 2 (Recommended)
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);//moves player upward regardless of velocity
I hoped that helped :)
Edit: After trying out the code you sent me it worked fine, but the 'jumpForce' was too low. I set the variable ('jumpForce') to 30 and it worked just fine. I coincidently I came across this video, the nostalgia from seeing this. Anyways, I couldn't figure out why you are having issues if 'jumpForce' isn't the case.
I recommend copying these 2D Rigidbody settings:
I created another script similar to the original, but probably much more readable for a beginner.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RevisedPlayerMovement : MonoBehaviour
{
[SerializeField] private float speed = 8f;//default is 8
[SerializeField] private float jumpForce = 30f;//default is 30
[SerializeField] private int maxJumps = 2;//default is 2
[SerializeField] private int jumps = 0;//the amount of jumps player has done
private bool isGrounded = true;//Checks if player is touching the ground - default true
private bool facingRight = true;//Checks if player is looking right - default true
SpriteRenderer sr;//the player's sprite renderer
Rigidbody2D rb;//the player's rigidbody
// Start is called before the first frame update
void Start()
{
/*Get Components - SpriteRenderer & Rigidbody2D*/
sr = GetComponent<SpriteRenderer>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move();
}
private void OnCollisionEnter2D(Collision2D col)
{
/*When Colliding With The Ground*/
if (col.gameObject.tag == "ground") {
isGrounded = true;
jumps = 0;
}
}
private void Move() {
/*Jump*/
if (Input.GetKeyDown(KeyCode.UpArrow) && jumps < maxJumps) {
isGrounded = false;
jumps++;
rb.velocity = Vector2.zero;
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
/*Moves Left and Right*/
if (Input.GetKey(KeyCode.RightArrow))//right
{
rb.velocity = new Vector2(speed, rb.velocity.y);
facingRight = true;
}
if (Input.GetKey(KeyCode.LeftArrow))//left
{
rb.velocity = new Vector2(-speed, rb.velocity.y);
facingRight = false;
}
Flip();
}
/*Flips Sprites On X-Axis Using SpriteRenderer Component*/
private void Flip() {
if (!facingRight)
sr.flipX = true;
else
sr.flipX = false;
}
}
Two things to note:
-[SerializeField]
just makes the variable visible in the inspector, so don't worry about it too much.
-The variable isGrounded
isn't used in any of the conditions (if-statements), but I included in case you need it for the future.
@muhammadaliawan96 Let me know if you still have troubles, I will create a prefab that you can download that should work when imported to your project.
@UnityTo$$anonymous$$ake$$anonymous$$oney i thank you for helping me out in this regard, i am not a programmer, it is my 1st time making a game and i am watching various youtube videos and reading here and there, i know nothing about coding, just learning as i work my way around. i have one question, the line you recommended, where should i put that in my code, can you please specify that little info. i apologize for being this silly. i once again thank you in this regard
update: i used the method 1 by replacing rb.velocity = Vector2.up * jumpForce; but it didnt work,
i replaced the same line with method 2, and it is still the same
There was a $$anonymous$$or error in $$anonymous$$ethod 2, 'Force$$anonymous$$ode' should be 'Force$$anonymous$$ode2D'. (See revised code below) I tested the code for both methods and it works fine for me. It may be that your variable 'jumpForce' doesn't have a high enough value and/or the settings on your rigidbody causes no upward movement.
Also, the location where you replace this would be in your if-statement to jump.
$$anonymous$$ethod 1:
if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps > 0)
{
rb.velocity = new Vector2(0 ,0);
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
}
$$anonymous$$ethod 2:
if (Input.GetKeyDown(KeyCode.UpArrow) && extraJumps > 0)
{
rb.AddForce(Vector2.up * jumpForce, Force$$anonymous$$ode2D.Impulse);
extraJumps--;
}
please let me know if this still isn't working. I remember being new to unity as well. Also, sorry for late responses. @muhammadaliawan96
@UnityTo$$anonymous$$ake$$anonymous$$oney , i thank you again from the core of my heart, you took time from your schedule and ran my code and guided me, but the from for me still exist, in player i added box collider and rigidbody2d, and only box collider to the ground. i tried your both suggested scripts but the problem doesnt seem to change for me. i still cant find a way to fix the problem. respected member, please guide me what settings you did with your player and rigid body and jump force so that i can follow that. thank you once again, and my apologies for late reply, it was night last day and now again evening, i get to wrok on this project at evenings.
@UnityTo$$anonymous$$ake$$anonymous$$oney, my apologies for getting here this late, it is almost a week by now, due to some of my other isseus, i couldnt work and get here, but i have just used your script, and i am really thankful to you for your kindness and help, the double jumps are working perfectly fine, when the player falls off of a platform it can jump twice. however, i must confess, i was working on adding various things to my character, such as shooting bullets, and the movement controller you provided were causing me some issues, so for the movement controller i switched back to my old script but i used your jump function, and now it can do all of it. i am really thankful to you for your help and kindness. i am not a programmer and as i am working, i am learning, right now m adding a dash/sprint attack function and later i would add respawn and life functions. i am once again really thankful to you for your help. many blessings.
Answer by muhammadaliawan96 · Oct 02, 2020 at 07:52 PM
@UnityToMakeMoney sir my apologies, i tried your code, i started a new clean project and used your code and all the settings you stated in rigidbody2d, the thing is, it now jumps twice while falling off the platform, the only issue now i face is, after jumping twice for 1st time, it cant jump anymore, i tried different things with the code, but it is not working, sir can you please help me in this regard? i am already thankful to you for what you did already.
Glad to hear that it is working for you!
As for
after jumping twice for 1st time, it can't jump anymore
I forgot to mention that the game objects that are ground/floor need to have the tag "ground". If you don't know how to add tags, watch this video.
If that doesn't work then I recommend that you add the following code in the Update method.
if(rb.velocity.y != 0)//if moving vertically
isGrounded = false;//not on ground
else
isGrounded = true;//on ground
However, you shouldn't have to modify the code in any way. I hope this finally resolves all your coding problems. :)
If you have any more questions about this or other things, let me know. I love to help!
@UnityTo$$anonymous$$ake$$anonymous$$oney, my apologies for getting here this late, it is almost a week by now, due to some of my other isseus, i couldnt work and get here, but i have just used your script, and i am really thankful to you for your kindness and help, the double jumps are working perfectly fine, when the player falls off of a platform it can jump twice. however, i must confess, i was working on adding various things to my character, such as shooting bullets, and the movement controller you provided were causing me some issues, so for the movement controller i switched back to my old script but i used your jump function, and now it can do all of it. i am really thankful to you for your help and kindness. i am not a programmer and as i am working, i am learning, right now m adding a dash/sprint attack function and later i would add respawn and life functions. i am once again really thankful to you for your help. many blessings. thank you sir.
No worries! I am more than happy to help :) I am very glad to hear you finally got things to work. I wish for the best in your future endeavors.
One piece of advice, I know you want to get things to work, but any experienced programmer will tell you that if your code works the first time, then something is wrong. Debugging is really difficult and it is a skill that many of the best programmers use. However, take the time to learn what each piece of code does and how to make it efficient. I would strongly recommend that you learn the Object Oriented Principles of computer science.
It's about quality, not quantity. You can learn 10 languages, but not be proficient in any, or know 1 or 2 languages and have mastery which can allow you to be proficient in more languages.
I hope you pursue coding and who knows, maybe we might meet face to face without even knowing it.
Your answer
Follow this Question
Related Questions
Is this the right way to do Double jumping? C# 1 Answer
Decrement with -- 1 Answer
Another Double Jump Question 0 Answers
how to stop double jumping in 2d platform effector 0 Answers
Trying to make a doublejump script, problems using rigidbody 1 Answer