- Home /
Question by
p4paul · Oct 17, 2017 at 07:07 AM ·
buttonjumponclickisgrounded
Can Someone Help me with my Onclick Jump Button to only fire only if Grounded
I made a UI button with onclick function set to Jump. Problem is it seems that the onclick event ignores my is Grounded Argument. What happens is that If I click on the button it endlessly jumps. This only happens if I use the button but it works fine if I use the spacebar. I just want my button to fire only if my Player is grounded.
Here is my script:
using UnityEngine; using System.Collections;
[RequireComponent(typeof(Rigidbody))] public class PlayerJump : MonoBehaviour {
public Vector3 jump;
public float jumpForce = 2.0f;
public bool isGrounded;
Rigidbody rb;
void Start(){
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
void Update(){
if(Input.GetKeyDown(KeyCode.Space) && isGrounded){
//rb.AddForce(jump * jumpForce, ForceMode.Impulse);
//isGrounded = false;
Jump();
}
}
public void Jump()
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
capture.png
(60.1 kB)
Comment
Best Answer
Answer by Dragate · Oct 17, 2017 at 07:12 AM
WIth your spacebar, you check isGrounded. WIth your UI button, you don't.
public void Jump(){
if(isGrounded){
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
WIth this you don't need to check isGrounded in Update(), as it's already done in Jump().