Hi I'm new to c# and i just made a code that allow the player to jump and it worked fine but the problem is if i clicked the space button twice it will do a douple jump and if i keep doing it will fly.... I just want a 1 jump and if the player hit the ground can jump again no double jump ... What i have tried is to change the number that Multiply with vector3.up to just jump and made a
public float jump = 5f;
also didnt work any way here is my source code hope you understand the problem and help me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
public float speed1;
public float jump = 5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * speed1);
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Rigidbody>().AddForce(Vector3.up * jump, ForceMode.VelocityChange);
}
}
}
You can create a flag wasGrounded which you will set false after jumping. The player can only jump, when wasGrounded == true.
You also add a collider to your ground. Once the player touched the ground, you reset the wasGrounded flag to true.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
public float speed1;
public float jump = 5f;
private bool wasGrounded = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * speed1);
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space) && wasGrounded)
{
wasGrounded = false;
GetComponent<Rigidbody>().AddForce(Vector3.up * jump, ForceMode.VelocityChange);
}
}
void OnCollisionEnter(Collision other)
{
// Change to string you compare it to to the tag of your ground gameobject.
if (other.gameObject.tag == "Ground")
{
wasGrounded = true;
}
}
}
Make sure to have "IsTrigger" set false on the ground`s collider.