I want 2 if statements to check if and if not colliding with a layer called ground for jumping in my 2d platformer. I tried to copy from the unity 2d platformer tutorial but that doesn’t seem to be working, any tips on how to check if colliding with a layer called ground
public void Jump(){
Debug.Log ("jump has also been called");
if (grounded) {
GetComponent<Rigidbody2D> ().velocity = Jumpforce;
Debug.Log("grounded is true");
public bool isGrounded;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.layer == 8 //check the int value in layer manager(User Defined starts at 8)
&& !isGrounded){
isGrounded = true;
}
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.layer == 8
&& isGrounded){
isGrounded = false;
}
}
Years later I am trying this and I can’t seem to get a collision based on layers to work.
Does anyone know why neither of these scripts would call the event or even show a debug log?
using UnityEngine;
using UnityEngine.Events;
public class LayerNumExample : MonoBehaviour
{
[Tooltip("check the int value in layer manager(User Defined starts at 8)")]
public int layerNumber = 8;
public UnityEvent layerEnterCollision;
public UnityEvent layerExitCollision;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.layer == layerNumber)
)
{
Debug.Log("Hit with Layermask");
layerEnterCollision.Invoke();
}
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.layer == layerNumber)
{
Debug.Log("Hit with Layermask");
layerEnterCollision.Invoke();
}
}
or
using UnityEngine;
using UnityEngine.Events;
public class LayerMaskExample : MonoBehaviour
{
public LayerMask layerMask;
public UnityEvent layerEnterCollision;
public UnityEvent layerExitCollision;
void OnTriggerEnter(Collider other)
{
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0)
{
Debug.Log("Hit with Layermask");
layerEnterCollision.Invoke();
}
}
void OnTriggerExit(Collider other)
{
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0)
{
Debug.Log("Left contact with Layermask");
layerExitCollision.Invoke();
}
}
}