Jumping only once (2D)
hey! I am a noob when coming to coding, I still don't know very much about C#, and I am having the trouble of my player only jumping once if I hit space again when it gets in the ground, it doesn't jump again
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public float Speed;
public float JumpForce;
public bool isJumping;
public bool doubleJump;
private Rigidbody2D rig;
// Use this for initialization
void Start () {
rig = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
Move();
Jump();
}
void Move () {
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * Speed;
}
void Jump () {
if(Input.GetButtonDown("Jump"))
{
if(!isJumping){
rig.AddForce(new Vector2(0f, JumpForce), ForceMode2D.Impulse);
doubleJump = true;
}else{
if(doubleJump){
rig.AddForce(new Vector2(0f, JumpForce), ForceMode2D.Impulse);
doubleJump = false;
}
}
}
}
void OnCollisionEnter2D(Collision2D collision){
if(collision.gameObject.layer == 8)
{
isJumping = false;
}
}
void OnCollisionExit2D(Collision2D collision){
if(collision.gameObject.layer == 8){
isJumping = true;
}
}
}
This is the code!! Many thanks if anyone can help me
Answer by DhirenC · Nov 20, 2020 at 08:15 PM
Hi Aserli, I think that the issue is that you are setting isJumping to true on OnCollisionExit2D, and false on OnCollisionEnter2D. I think that for your case you want to set isJumping to true on OnCollisionStay2D and OnCollisionEnter2D and set it to false on OnCollisionExit2D. This way your jump is reset on contact with an object and is disabled when you leave the ground.
Your answer
Follow this Question
Related Questions
Problems with jumping in Doodle Jump like game 2 Answers
How i make a ball jump where i point with my mouse?[3D] 0 Answers
jumping for different characters? 0 Answers
How to make my ball jump? 1 Answer
Jump Using Raycast. 0 Answers