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();
}
// 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
}
}
}
↧