W
W
WinstonTails2021-12-29 02:19:53
Unity
WinstonTails, 2021-12-29 02:19:53

How to implement a jump in a 2D game?

I tried to implement a jump in a 2D game and at the start of the project the character flew into the sky without pressing the spacebar

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

public class Move : MonoBehavior
{
public Rigidbody2D physic;

private bool isGrounded;
private float groundRadius = 0.7f;

public Transform GroundCheck;
public LayerMask groundMask;

void Start()
{

}

void Update()
{

transform.Translate(Vector3.right * 0.1f);

isGrounded = Physics2D.OverlapCircle(GroundCheck.position, groundRadius, groundMask);

if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true) ;
{
physic.AddForce(new Vector2(0, 10));
}


} }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Farawa, 2021-12-29
@Farawa

Firstly, why is there a ";" after the condition for the click test? Second, add to addforce the second parameter forcemode.impulse

N
Nekit Medvedev, 2021-12-29
@NIKROTOS

void Update()
{
transform.Translate(Vector3.right * 0.1f);

In this line, every frame you move something, and without any conditions.
By the way, why do you use Vector3 in a 2D game? (most likely this is the problem)
Well, if you don’t know where the error is, then add variables, by the value of which you can determine in what state the object is.
For example:
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true) ;
{
physic.AddForce(new Vector2(0, 10));
isSpace=true;
}

So you can definitely understand if there is an error in this segment of the program (isSpace should be displayed in the inspector).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question