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");
Could you provide us with some code of what you have been trying?
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;
}
}
I added a debug.log to log if collided with layer and it's not logging when exiting or entering.
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();
}
}
}
Nevermind, I see I had my comments off in the Console and another way to check the layer mask is if ((layerMask.value & (1 << other.transform.gameObject.layer)) != 0) You can also select multiple layers in the dropdown so this is preferable to the int layerNumber method.
Could you provide us with some code of what you have been trying?
– BlukYeah. Include (a part of) your script so we can see what's going on..
– imilanspinkaAre you creating a game called sqarey jump like me from the youtube channel named 'Android Authority'?
– reyansh_shivnani