M
M
Mr_Keks2019-02-05 18:17:37
C++ / C#
Mr_Keks, 2019-02-05 18:17:37

How to do TWO jumps in Unity platformer?

In short, in my Unity platformer, a character can jump in the air. How to deal with it?
HELP ME PLEASE!!!!!!!!!!!!!
The code:

using UnityEngine;

public class PlrCntrl : MonoBehaviour
{
    public float speed = 20f;
    private Rigidbody2D rb;
    private bool faceRight = true;
    public int JumpForce;
    
    

    

    void Start()
    {
        
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        
        float moveX = Input.GetAxis("Horizontal");
        rb.MovePosition(rb.position + Vector2.right * moveX * speed * Time.deltaTime);
        //прыжок от пробела
        if (Input.GetKeyDown(KeyCode.Space))
            
               rb.AddForce(Vector2.up * JumpForce );
        
            
        


        if (moveX > 0 && !faceRight)
            flip();
        else if (moveX < 0 && faceRight)
            flip();
    }
    void flip ()
    {
        faceRight = !faceRight;
        transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Gaydak, 2019-02-05
@MrMureno

standard platform controller from standard assets..contains an example and a bunch of tutorials.
a check is made for "touching the ground". a jump can only be made if after the jump there was a "touch of the ground. and from here a double jump is already dancing, and so on..
https://unity3d.com/ru/learn/tutorials/topics/2d-g...
for example here they seem to determine the direction .. but the essence is still in the grounded flag

N
Nikita Kirakosyan, 2019-02-07
@Noomank

Make a check to see if the object has something under its feet and, if so, jump.
If you need a detailed explanation, then read
"Unity in action. Multi-platform development in c#" by Joseph Hawking: https://www.ozon.ru/context/detail/id/34792570/
PS
In your case:

using UnityEngine;

public class PlrCntrl : MonoBehaviour
{
    float force = 100.0f;
    bool grounded;

       private void Update()
{
    if(grounded == true){
    transform.GetComponent<Rigidbody2D>().AddForce(transform.up * force);
}
}
}

Just describe a function where grounded takes on different values ​​depending on the location of the character.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question