V
V
Vasya Pupkin2022-02-06 16:17:14
C++ / C#
Vasya Pupkin, 2022-02-06 16:17:14

How to add code so that a player without support cannot jump?

In unity, a beginner, I work in 2D, I ran into such a problem that if you hold down the space bar, the character will fly up indefinitely. We need the code to check if there is a sprite with the Box Collider 2D component under the character, and then perform a jump, if not, it is idle.

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

public class controller : MonoBehaviour
{
    [Header("Player velocity")]
    public int xVelocity = 5;
    public int yVelocity = 8;

    private Rigidbody2D rigidBody;

    private void Start()
    {
        rigidBody = gameObject.GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        updatePlayerPosition();
    }

    private void updatePlayerPosition()
    {
        float moveInput = Input.GetAxis("Horizontal");
        float jumpInput = Input.GetAxis("Jump");

        if (moveInput < 0)
        {
            rigidBody.velocity = new Vector2(-xVelocity, rigidBody.velocity.y);
        }
        else if (moveInput > 0)
        {
            rigidBody.velocity = new Vector2(xVelocity, rigidBody.velocity.y);
        }

        if (jumpInput > 0)
        {
            rigidBody.velocity = new Vector2(rigidBody.velocity.x, yVelocity);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LittleBob, 2022-02-06
@Dimoncheck

Don't thank
https://youtu.be/mjaoJ1rDoaQ

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question