Why Does My Script Allow Double-Jumping?
Hello people, I'm trying to write a simple script to make my character jump on top of what is taught in Roll a Ball tutorial. I looked for some help in this website to write this jumping script but for some reason it's allowing my player to doublejump. Any help would be appreciated :)
Also does OnCollusionStay somehow "know" what is ground or does it simply turn back to true on any collusion event? How do I introduce e.g. "MyGroundPlane" GameObject to the code?
Thanks.
(Edit: Spelling.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour {
Rigidbody rb;
public float speed;
public float jumpForce;
public Vector3 jump;
public Vector3 movement;
public bool isGrounded;
void Start () {
rb = GetComponent<Rigidbody>();
speed = 10;
jumpForce = 5;
}
private void OnCollisionStay(Collision collision)
{
isGrounded = true;
}
void FixedUpdate () {
//Move
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
movement = new Vector3(moveHorizontal * speed, 0, moveVertical * speed);
rb.AddForce(movement);
//Jump
jump = new Vector3(0, jumpForce, 0);
if (Input.GetKeyDown("space") && isGrounded == true)
{
rb.AddForce(jump, ForceMode.Impulse);
isGrounded = false;
}
}
}
Answer by Cuttlas-U · Apr 06, 2017 at 08:37 PM
hi u can check if u had collision with the ground object by using tag assign a tag to the ground object then compare if u really hit the right object:
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.tag =="your tag")
isGrounded = true;
}
this way u are sure u hit the ground;
Answer by mnarimani · Apr 06, 2017 at 08:23 PM
OnCollisionStay as it is right now, doesn't care what you hit, it will set isGrounded to true, what I recommend is to add this in FixedUpdate and remove OnCollisionStay:
isGrounded = Mathf.Abs(rb.velocity.y) < 0.1;
Your answer

Follow this Question
Related Questions
How to fix this problem? 1 Answer
Collision Detection with DrawMeshInstanced 0 Answers
Real aerodynamics moving surfaces 0 Answers
Bounce between two exact points 1 Answer