- Home /
calling jump as a ui button function, how to detect ground within the function?
Thank you everyone in advance for any help. I am self learning to code and use unity. I have the following simple jump function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpButton : MonoBehaviour {
public float jumpSpeed;
private Rigidbody rb;
private int count;
//Adding the boolean variable onPlane to check if object touching the ground tag
private bool onPlane;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
//make onPlane true
onPlane = true;
}
void FixedUpdate()
{
//If onPlane true you can jump
if (onPlane)
{
if (Input.GetKey(KeyCode.Space))
{
rb.velocity = new Vector3(0f, jumpSpeed, 0f);
onPlane = false;
}
}
}
//after the object touches the floor again, make onPlane true(I think I need to replicate this in the function somehow?)
private void OnCollisionEnter(Collision collision)
{
//My plane is actually tagged Ground
if (collision.gameObject.CompareTag("Ground"))
{
onPlane = true;
}
}
public void canjump()
{
//I can use an if statement here to check onPlane state.
if(onplane)
{
rb.velocity = new Vector3 (0f, jumpSpeed, 0f);
} onPlane = false;
//I think that I need another if statement of sorts here, but am not sure what I can do exactly }
public void cannotjump(){
}
}
This is attached to my player character, and the ui button is linked and calling the function. I can jump fine, but I can not jump again after landing. (Not my intention) I know that setting the on plane to fall will disable the jump, but how to I re-enable it within the same function after the player has again landed on the plane? I have tried so many ways the past two days, going crazy lol.
Any help would be much appreciated, can't get my head around this one for some reason, maybe lack of sleep. Only been using unity for 4 months, this is my 4th project. Going to kick myself probably if the answer if something simple.
This question is a little messy so it's hard to read out what the problem is... First things first though you have if(onplane)
and not if(onPlane)
in your canjump
method.
Check if that's the problem and/or the only problem and edit the question so it's a little more clear!
Your answer
Follow this Question
Related Questions
Raycasting bug when checking if player is grounded 2 Answers
Jump if ground is detected 1 Answer
Player can jump on non ground items 1 Answer