- Home /
OnTriggerEnter2D randomly stops detecting
I am using a Trigger to detect when the player lands on the ground after jumping but the issue is after jumping for a while the trigger will randomly stop detecting the ground and make it to where the player can not jump anymore
using UnityEngine;
public class charController : MonoBehaviour
{
Transform Horizontal;
public Rigidbody2D Player;
public float speed = .2f;
public float jumpHight = .3f;
bool isGround = true;
void FixedUpdate ()
{
float HorAxis = Input.GetAxis("Horizontal");
Vector2 Movment = new Vector2(HorAxis , 0);
transform.Translate(Movment * speed);
if (Input.GetKeyDown(KeyCode.Space) && isGround == true)
{
Player.AddForce(Vector2.up * jumpHight);
isGround = false;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Floor")
{
isGround = true;
}
}
}
Answer by Dalsia · Jan 21, 2018 at 11:59 PM
There are a few things you could try. For one, try OnCollisionEnter2D or OnCollisionStay2D, as that might produce more consistent results.
You could also make it so that you can only jump when velocity.y == 0, that way you will only jump when you're on the ground, and won't necessarily need bools to tell you when you can jump.
Thank you I spent so long trying to figure out why the script is not working. Fixed by such a little change.
Your answer
Follow this Question
Related Questions
Why can't void be used in this context? 2 Answers
triggering random animations with gui 1 Answer
Randomly spawn a trigger area 1 Answer
Spawn Random Item On Trigger Enter 2 Answers