Answer the question
In order to leave comments, you need to log in
How to make one jump to Unity2D platformer? When you hold W, it starts to fly, how to limit it to one jump?
using UnityEngine;
public class Hero : MonoBehavior
{
[SerializeField] private float speed;
public float force;
public Rigidbody2D rigidbody;
void Update()
{
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.W))
{
rigidbody.AddForce(Vector2.up * force, ForceMode2D.Impulse);
}
}
}
Answer the question
In order to leave comments, you need to log in
You can either check "whether it's on the ground", as they do in the tutorials, or just do a cooldown
. Here's the cooldown:
[SerializeField] private float speed;
public float force;
public Rigidbody2D rigidbody;
public float timeCoolDown; //Collapse time
private bool heJumped = false; //Check "Did the player jump?"
void Update()
{
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.W) && heJumped == false)
{
rigidbody.AddForce(Vector2.up * force, ForceMode2D.Impulse);
StartCoroutine(CoolDown());
}
}
IEnumerator CoolDown()
{
heJumped = true;
yield return new WaitForSeconds(timeCoolDown);
heJumped=false;
}
the code has not been checked, so if there are errors - write
Here is the ground check:
[SerializeField] private float speed;
public float force;
public Rigidbody2D rigidbody;
public bool isGrounded; //Check "Whether the player is on the ground"
void Update()
{
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.W) && isGrounded == true)
{
rigidbody.AddForce(Vector2.up * force, ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question