- Home /
How to ground check?
I'm having trouble with my code for ground checking to avoid the rocket ship effect when pressing space in the game.
This is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private bool isGrounded;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * 7f, rb.velocity.y);
if (Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector2(rb.velocity.x, 7f);
}
if (!isGrounded)
{
return;
}
}
private void OnCollisionEnter(Collision collision)
{
isGrounded = true;
}
private void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}
Comment
Answer by Hawaii_Dev · May 16 at 02:43 PM
You have a rigidbody meant for 2D but use functions for 3D. Change OnCollisionEnter to OnCollisionEnter2D and OnCollisionExit to OnCollisionExit2D. The 2D physics is separate from 3D and I have seen a lot of people get confused with these functions. @jrdymally