E
E
Evgeny Zaletsky2021-02-09 23:56:35
C++ / C#
Evgeny Zaletsky, 2021-02-09 23:56:35

How to make a check that the character is on the ground?

Hi all! I can’t make the character not do a double jump (there were no constant jumps)
I tried to check for tags through raycast, but nothing helps, so I decided to ask for advice.

spoiler
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HeroScript : MonoBehaviour
{

    public float horizontalSpeed;
    float speedX;
    public float verticalimpulse;

    public LayerMask groundLayer;


    Rigidbody2D rb;

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

        
        Vector2 position = transform.position;
        Vector2 direction = Vector2.down;
        float distance = 1.0f;
        Debug.DrawRay(position, direction, Color.black);
        RaycastHit2D hit = Physics2D.Raycast(position, direction, distance, groundLayer);
        if (hit.collider != null)
        {
            return true;
        }

        return false;
    }




    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.A))
        {
            speedX = -horizontalSpeed;
            transform.localScale = new Vector3(-1, 1); //Персонаж смотри в ту сторону, куда нажал игрок

        }
        else if (Input.GetKey(KeyCode.D))
        {
            speedX = horizontalSpeed;
            transform.localScale = new Vector3(1, 1); //Персонаж смотри в ту сторону, куда нажал игрок
        }
        

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();  
        }
        transform.Translate(speedX, 0, 0);
        speedX = 0;
    }
    void Jump()
    {
        if (!IsGrounded())
        {
            return;
        }
        else
        {
            rb.AddForce(new Vector2(0, verticalimpulse), ForceMode2D.Impulse);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CHIDWI, 2021-02-18
@CHIDWI

bool isJump;

private void Update()
{
        if (Input.GetKeyDown("space") && !isJump) //проверка на нажатие кнопки и не находимся ли мы в прыжке сейчас
        {
//вызываем прыжок AddForce или что там у вас.
            isJump = true; //помечаем флаг, что мы прыгнули
        }
}

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "ground") //проверка что обьект столкновения имеет тег ground
        {
            isJump = false; //помечаем что мы столкнулись с землёй и можем снова прыгать
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question