Hi I would like to add semi-permeable objects to the platformer I am creating. That is, an object that when the player stands on, it will slowly sink until it falls completely.
The first version of the script for this behavior looks like this :
[SerializeField] private GameObject player;
[SerializeField] private float fallingSpeed = .1f;
[SerializeField] private float AngulaDrag = 2.5f; //This is a linearDrag
private bool isOnSemiPermeableObject = false;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
isOnSemiPermeableObject = true;
Physics2D.IgnoreCollision(collision, player.GetComponent<Collider2D>(), true);
player.GetComponent<Rigidbody2D>().gravityScale = 0;
player.GetComponent<Rigidbody2D>().drag = AngulaDrag;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
isOnSemiPermeableObject = false;
Physics2D.IgnoreCollision(collision, player.GetComponent<Collider2D>(), false);
player.GetComponent<Rigidbody2D>().gravityScale = 3;
player.GetComponent<Rigidbody2D>().drag = 0;
}
}
// Update is called once per frame
void Update()
{
if(isOnSemiPermeableObject)
{
player.transform.Translate(Vector3.down * fallingSpeed * Time.deltaTime);
}
}
And it actually looks pretty good, I need to tweak AngularDrag a bit, but that’s not important right now. Also note the absence of the Awake method, where it will initialize the player’s Rigidbody.
What bothers me, though, is that the box collider of the semi-permeable object interacts with the entire player collider. And I would need it to only interact with the bottom of the player’s collider. That is, once the player’s feet are outside the semi-permeable object, so that the player gains normal speed and quickly falls to the ground, hence the OnColliderExit action occurs.
The way it currently works is that the gravity and angular resistance values only return to normal after the semi-permeable object leaves the player’s entire collider.