A
A
Alexey Fedorov2017-04-21 08:34:21
2D
Alexey Fedorov, 2017-04-21 08:34:21

Jumping in Unity. How to make a character jump once?

When you press the spacebar, the character jumps, but if you press the spacebar again during the flight, he will jump higher and so on until you press the spacebar. How to make a character jump once?

using UnityEngine;
using System.Collections;

public class Character : MonoBehaviour
{
    [SerializeField]
    private int lives = 5;
    [SerializeField]
    private float speed = 3.0F;
    [SerializeField]
    private float jumpForce = 15.0F;

    private bool isGrounded = false;

    new private Rigidbody2D rigidbody;
    private Animator animator;
    private SpriteRenderer sprite;

    private void Awake()
    {
        rigidbody = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        sprite = GetComponentInChildren<SpriteRenderer>();
    }

    private void FixedUpdate()
    {
        CheckGround();
    }

    private void Update()
    {
        if (Input.GetButton("Horizontal")) Run();    }

    private void Run()
    {
        Vector3 direction = transform.right * Input.GetAxis("Horizontal");

        transform.position = Vector3.MoveTowards(transform.position, transform.position + direction, speed * Time.deltaTime);

        sprite.flipX = direction.x < 0.0F;
    }

    private void Jump()
    {
        rigidbody.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
    }

    private void CheckGround()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.3F);

        isGrounded = colliders.Length > 1;
    }
}

Answer the question

In order to leave comments, you need to log in

5 answer(s)
K
Konstantin Kavensky, 2017-04-21
@awlbrut1

Leave it as a killer feature

D
Dmitry, 2017-04-21
@TrueBers

state pattern

E
Eugene, 2017-04-21
@Eugeny1987

Check that he is on the surface, then let him jump

A
Alex Maximovich, 2017-04-21
@flexer1992

https://habrahabr.ru/post/212309/
In this article you will find the answer to your question)

A
al3x69, 2019-01-21
@al3x69

God, just check the velocity of the sprite's movement, if velocity.y != 0, then write return in the method for adding an impulse, otherwise add an impulse

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question