Hello! I have a problem with my script : I want my player to jump only when he is on the ground. But my script doesn’t work, can you please tell me what’s is wrong with him?
I’m new with scripting, i’m really a beginner. The original code is from the unity tutorial “roll-a-ball”.
My technique is to declare a boolean called “canjump” who become true only when he is on a game object with the tag “ground”. When the boolean is true and the player press the jump button, the avatar jump.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerController : MonoBehaviour {
private Rigidbody rb;
public Text countText;
public Text WinText;
public float speed;
private int count;
public float upper = 9.0F;
public bool canjump = false; // boolean for jump
void Start ()
{
rb = GetComponent ();
count = 0;
SetCountText ();
WinText.text = “”;
canjump = false; // the boolean is false by default
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis (“Horizontal”);
float movevertical = Input.GetAxis (“Vertical”);
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, movevertical);
rb.AddForce (movement * speed);
if ((canjump == true) && (Input.GetButton (“Jump”))) //if canjump boolean is true and if the player press the button jump , the player can jump.
{
Vector3 up = new Vector3 (0.0f, upper, 0.0f); // script for jumping
rb.AddForce (up * upper);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag (“Pick Up”))
{
other.gameObject.SetActive(false);
count++;
SetCountText ();
}
if (other.gameObject.CompareTag (“ground”))// if the player is touching the gameobject with the Tag ground, the boolean become true
{
canjump = true;
}
else //if the player is not anymore on the ground, the boolean become false
{
canjump = false;
}
}
void SetCountText ()
{
countText.text = "Count: " + count.ToString ();
if (count >= 8)
{
WinText.text = “You Win!”;
}
}
}