- Home /
Collider doesn't work always
Hi there! I'm using this script for player (ball) movement and I'm using colliders to check if a player can jump or he cannot. But this colliders doesn't work always so as a result I have a situation when player IS on a ground but he CAN NOT jump. Any ideas? Thanks!
using UnityEngine;
using System.Collections;
public class BallMovement : MonoBehaviour {
public float speed;
public float jumpSpeed;
bool CanJump;
bool jump;
void Start ()
{
CanJump = true;
jump = false;
}
void OnCollisionExit(Collision collisionInfo)
{
CanJump = false;
jump = false;
}
void OnCollisionEnter(Collision collisionInfo)
{
CanJump = true;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && CanJump == true)
{
jump = true;
}
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rigidbody.AddForce(movement * speed * Time.deltaTime);
if (jump == true)
{
rigidbody.AddForce(Vector3.up * jumpSpeed);
}
}
}
Is there anything else he can collide with besides the floor? If so, your code needs to be conditional on the floor since CanJump will get turned on/off by other objects. This problem is more typically solved by Raycasting down.
Answer by MrSteve1 · Aug 08, 2014 at 01:29 PM
I has this issue with my project, drove me nutty for ages. Try using
OnCollisionStay, rather than OnCollisionEnter (Enter only if something is colliding in the 1 particular frame, Stay checks more every frame that there is a collision).
Hope this helps you out.