I'm sure this is down to my lack of understanding of the unity physics system.
I'm trying to implement a simple one-way platform for a 2d game and have got stuck on creating a reliable way to let the character 'drop down' from a platform on pressing the down arrow.
While trying to debug and whittle down the code, I've found myself with this strange debug script:
using UnityEngine;
using System.Collections;
public class DebugPlatform : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D other)
{
if(Physics2D.GetIgnoreLayerCollision (other.collider.gameObject.layer, this.gameObject.layer))
print ("ERROR: How does this happen?!!");
else
print("This is normal.");
}
}
When I place this on my one way platform and mess about in game, sometimes the character refuses to drop down on command, and the error message is printed.
From what I understood, GetIgnoreLayerCollision returned whether the collisions between the layers were being ignored or not.
So my questions are:
- Why is OnCollisionEnter2D being called even though the layers are supposed to be ignored?
- Is this ignore value just a request, not absolute? Maybe some collision optimization that I have to override?
- I can't imagine this is some multi-threading issue, as the error appears regularly, after I do a normal jump on the platform.
- Am I doing something completely wrong?
EDIT: Extra info: The one way platform is two parts, first an if else in FixedUpdate in the player script:
// Don't collide with platforms if flag is set or we are moving up:
if (ignorePlatform || transform.rigidbody2D.velocity.y > 0f)
Physics2D.IgnoreLayerCollision (PlayerLayerID, PlatformLayerID, true);
else if(transform.rigidbody2D.velocity.y <= 0f)
Physics2D.IgnoreLayerCollision (PlayerLayerID, PlatformLayerID, false);
The platform has an EdgeCollider2D on the top and a child with a Collider2D trigger underneath. A script then resets the player's ignorePlatform to false on exit. This is to make sure the player only falls through one platform when the down arrow is pressed.
transform.rigidbody2D.velocity.y <= 0f
\$\endgroup\$