I am creating a game in which the player controls a ball. I was able to make a script in which the ball can jump, but if you keeping pressing the spacebar, it will continue to go up. I am not very experienced with C# so I’m not sure how to put a limit on how much the player can jump. After viewing my script, if you think you have a better jump script or know how to limit the jumps, please tell me. Also, if you need to look at my camera and player control (movement) scripts, I will provide those. Here is my script:
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour
{
public float jump;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
this.GetComponent<Rigidbody>().AddForce(new Vector3(0, jump, 0));
}
}
}
hi here is your code and one advice be more learner and exploring unity learn in start.
you have to add “Ground” tag to your terrain or any thing that is ground… .
(Y)
public class Jump : MonoBehaviour
{
public float jump;
private bool is ground;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && Ground)
{
ground = false;
this.GetComponent<Rigidbody>().AddForce(new Vector3(0, jump, 0));
}
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Ground"){
ground = true;
}
}
hi here is your updated code . just add Tag “ground” to your terrain or ground.
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour
{
public float jump;
private bool isGround;
// Use this for initialization
void Start()
{
isGround = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGround)
{
isGround = false;
this.GetComponent<Rigidbody>().AddForce(new Vector3(0, jump, 0));
}
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "ground"){
isGround = true;
}
}
}