- Home /
How to keep ball from jumping more than once?
I am trying to make a ball jump as it is rolling but when it is rolling, the isGrounded bool keeps flashing on and off. Why and how do I fix it? I would appreciate any help at all.
C# preffered.
public class Jump : MonoBehaviour {
public float jumpForce = 10.0f;
public bool isGrounded;
public Collider groundCollider;
float jumpWaitTime = 1.0f;
private float nextJumpTime;
// Use this for initialization
void Start ()
{
isGrounded = true;
}
//performs a jump
public void JumpFunction()
{
Vector3 jump = new Vector3(0.0f, jumpForce, 0.0f);
rigidbody.AddForce(jump, ForceMode.Impulse);
}
// Update is called once per frame
void Update ()
{
if (Physics.Raycast(transform.position, -transform.up, 2))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
//jump if player presses Jump
if(Input.GetButtonDown("Jump") && isGrounded && Time.time >= nextJumpTime)
{
isGrounded = false;
JumpFunction();
nextJumpTime = Time.time + jumpWaitTime;
}
// manually set isGrounded to true
if(Input.GetKeyDown(KeyCode.U))
{
isGrounded = true;
}
}
void FixedUpdate ()
{
}
void onCollisionStay(Collider groundCollider)
{
isGrounded = true;
}
}
Well, is it because isGrounded
gets changed in the if (Physics.Raycast(transform.position, -transform.up, 2))
condition? If so, are you sure 2 is enough? And is -transform.up
always pointing at whatever the ball is rolling on?
You can use some Debug.Log lines in your code, every time isGrounded can change. That way, you will know what is going on. In my opinion it is the raycast that can't stop changing the value, but I don't know why yet...
Answer by anirudhp9708 · Jan 21, 2017 at 06:45 AM
@ c====3 Yo bro, I got it. Although I used movement only for horizontal axis.. :)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BallControl : MonoBehaviour {
public float speed;
public int jumpHeight = 8;
private bool isfalling = false;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
isfalling = false;
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, 0.0f);
rb.AddForce(movement * speed);
if (Input.GetKeyDown(KeyCode.W) && isfalling == false)
{
rb.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse);
}
isfalling = true;
}
void OnCollisionStay(Collision groundcollider)
{
isfalling = false;
}
}
Your answer
Follow this Question
Related Questions
Grounded bool acting weird 1 Answer
jump on collision - first person controller 0 Answers
Jumping on top of an enemy problem 1 Answer
Character jump on collision 1 Answer
Check if skateboard is grounded 1 Answer