My sphere won't always jump when space is pressed
Hey all!
Let's get right to it:
I made the roll-a-ball thing, like a lot of people did, and then I started bolting things on, which I assume a lot of people did as well. Here's where I'm currently stuck:
Right now I have a raycast pointing straight down at 0.9 length, to check to see if the ball is grounded. If it is, it sets "grounded" to "true"
If "grounded" is true, and you hit Space, you should jump.
The "grounded" bool works great. I have it public, so I can watch it check every time.
The weird thing is, this only happens some of the time. The grounded checkbox will be checked, and jump does nothing. If you keep rolling around and try some more, eventually you'll start jumping. Seems to come and go. At this point, I'm assuming I am using a wrong way to make the sphere jump. I want it to keep momentum, but just pop into the air in whatever direction the player is rolling.
Here's what I've got:
//player movement variables
private float speed = 10f;
private float jumpForce = 20f;
public bool grounded;
private RaycastHit hit;
private float dist;
private Vector3 direction;
private float airControlModifier = 0.1f;
void Start ()
{
Debug.Log ("Level name is: " + Application.loadedLevelName);
rb = GetComponent<Rigidbody> ();
grounded = false;
}
void Update (){
dist = 0.9f;
direction = Vector3.down;
Debug.DrawRay(transform.position,direction*dist,Color.green);
if (Physics.Raycast (transform.position, direction, dist)) {
grounded = true;
} else {
grounded = false;
}
}
// update every physics frame
void FixedUpdate ()
{
// get Axis input
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
//see if player is grounded, if not, modify the movement speed, and either way, add force to player
if (grounded == true) {
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement*speed);
}
else {
Vector3 movement = new Vector3 (moveHorizontal * airControlModifier, 0.0f, moveVertical * airControlModifier);
rb.AddForce (movement*speed);
}
// Jump with space bar
if (Input.GetKeyDown (KeyCode.Space) && grounded == true) {
//rb.velocity = new Vector3 (moveHorizontal, jumpForce, moveVertical);
Vector3 movement = new Vector3 (moveHorizontal, jumpForce, moveVertical);
rb.AddForce (movement*speed);
}
Answer by mblissmer · Sep 05, 2015 at 06:46 PM
And of course the second I ask the question, a lightbulb goes off and I solve it.
I moved the jump command up to Update instead of Fixed Update. Since GetKeyDown only triggers for that single frame, Fixed Update was missing them randomly.
I moved it to Update and BAM. Works great!