- Home /
Check if colliding with a layer
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?
Yeah. Include (a part of) your script so we can see what's going on..
Are you creating a game called sqarey jump like me from the youtube channel named 'Android Authority'?
Answer by Positive7 · Aug 06, 2015 at 02:52 PM
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.
Answer by Krnitheesh16 · Sep 02, 2021 at 05:58 AM
Using the bitwise operator you can able to find collisions with a layer mask.
public LayerMask layerMask;
private void OnTriggerEnter(Collider other) {
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0) {
Debug.Log("Hit with Layermask");
}
else {
Debug.Log("Not in Layermask");
}
}