Question by
Bilal_Aljandly · Oct 05, 2021 at 08:25 AM ·
movementtimejumpif-statementsloops
how can i repeat an if statment for x sec?
Hi! I trying to make the Player jump if it is grounded and if the player isn't grounded check if the Player will be grounded in the next x sec. So if the Player become grounded i the x sec it will jump.
The First Part is working will but the checking for x sec part I don't know how to do it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movements : MonoBehaviour
{
[SerializeField] Rigidbody2D rg;
[SerializeField] float movementSpeed;
[SerializeField] float maxSpeed;
[SerializeField] float jumpForce;
[SerializeField] float raydis;
[SerializeField] LayerMask GroundLayerMask;
public float jumpCheckingTime = 0.3f;
// Start is called before the first frame update
void Start()
{
rg = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
Jump();
}
private void FixedUpdate()
{
float moveX = Input.GetAxis("Horizontal");
if(Input.GetKey(KeyCode.A) && rg.velocity.x > -maxSpeed)
rg.AddForce(new Vector2(moveX * movementSpeed, 0f), ForceMode2D.Force);
if(Input.GetKey(KeyCode.D) && rg.velocity.x < maxSpeed)
rg.AddForce(new Vector2(moveX * movementSpeed, 0f), ForceMode2D.Force);
}
bool IsGrounded()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, raydis, GroundLayerMask);
if (hit.collider != null)
{
if (hit.collider.tag == "Ground")
{
return true;
}
else return false;
}
else
{
return false;
}
}
void Jump()
{
if (IsGrounded())
{
rg.velocity = new Vector2(rg.velocity.x, 0f);
rg.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
else
{
// Check for x Sec is the player will be grouned
}
}
}
Comment
Best Answer
Answer by Hellium · Oct 05, 2021 at 08:56 AM
CODE NOT TESTED
[SerializeField] float jumpRequestBufferDuration = 0.2f;
float lastJumpRequestTime = Mathf.NegativeInfinity;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) || Time.timeSinceLevelLoad < lastJumpRequestTime + jumpRequestBufferDuration)
Jump();
}
void Jump()
{
if (IsGrounded())
{
rg.velocity = new Vector2(rg.velocity.x, 0f);
rg.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
lastJumpRequestTime = Mathf.NegativeInfinity;
}
else
{
lastJumpRequestTime = Time.timeSinceLevelLoad;
}
}
thanks, it did work. I will be grateful if you can explain how it is working
The code is pretty simple.
When jump is requested, if the character is not grounded, I save the time.
In Update, I check whether the request time was less than jumpRequestBufferDuration
seconds ago (i.e if the current time is less than the request time + buffer duration)
if(Time.timeSinceLevelLoad < lastJumpRequestTime + jumpRequestBufferDuration)
is the same as
if(lastJumpRequestTime > Time.timeSinceLevelLoad - jumpRequestBufferDuration