so I started unity literally yesterday meaning this is my second day. I followed a tutorial to make a movement script, but when I continuously press space, I can jump like infinitely. This is my code below, is there any way to fix the infinite jump to just two jumps and then it resets when it hits the ground?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if (Input.GetKey(KeyCode.Space))
body.velocity = new Vector2(body.velocity.x, speed);
}
}
CodePudding user response:
You can prevent this by adding time delay
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
[SerializeField] private float speed;
[SerializeField] private float jumpTimeDelay = 0.5f; // feel free to increase or decrease
private const float timeDelayConst = jumpTimeDelay;
private bool isGrounded = false;
private Rigidbody2D body;
private void Awake() {
body = GetComponent<Rigidbody2D>();
}
private void Update(){
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed,
body.velocity.y);
isGrounded = jumpTimeDelay <= 0;
jumpTimeDelay -= Time.time;
if (Input.GetKey(KeyCode.Space) && isGrounded){
body.velocity = new Vector2(body.velocity.x, speed);
jumpTimeDelay = timeDelayConst;
}
}
}
CodePudding user response:
This is easily done by adding a boolean value to check if the player is grounded or not and change the value when player jumps. You also need to add a tag to your ground object so we can check if the player is touching the ground. To add tags to objects please refer to Unity - Manual: https://docs.unity3d.com/530/Documentation/Manual/Tags.html
Just for future these kind of questions are asked a lot so you can pretty much google your question and find similar answers.
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private bool isGrounded = true;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if(Input.GetKey(KeyCode.Space))
{
if (isGrounded)
{
isGrounded = false;
body.velocity = new Vector2(body.velocity.x, speed);
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground") {
isGrounded = true;
}
}
}