2D Platformer: Failure to jump through platform
Hi! I'm working on a 2D platformer right now in Unity 2021.1.17f1, and I would like the player to be able to jump through specific (tagged) platforms when they press the down key. Unfortunately, nothing is exactly working, and I've tried quite a bit (see: 1, 2, 3, 4, 5, 6). This is something like day six of the same headache.
The code below is the most "normal" gameplay possible, but it also isn't perfect. The player can clip through the floor and then fall off the map. Trying to combine the Drop Platform tag with pressing the Down key never fired correctly: the Debug.Log statements would only return about 30% of the time. I am not sure why.
The player has a Capsule collider. The platforms all have box colliders and platform effectors that allow the player to jump up through the bottom and then walk on top of them, which I would also like to keep! I just can't figure out how to let the player jump down. I have tried using triggers. It did not work.
Any advice possible would be greatly appreciated.
public float waiting = 0.5f;
public bool droppable = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.DownArrow))
{
StartCoroutine(FallTimer());
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
GetComponent<CapsuleCollider2D>().enabled = true;
}
}
IEnumerator FallTimer()
{
GetComponent<CapsuleCollider2D>().enabled = false;
GetComponent<Rigidbody2D>().gravityScale += 4; //falls faster
yield return new WaitForSeconds(waiting); //waits a variable amount of time before re-enabling capsule collider
GetComponent<CapsuleCollider2D>().enabled = true;
GetComponent<Rigidbody2D>().gravityScale -= 4;
}
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "Drop Platform")
{
//GetComponent<CapsuleCollider2D>().isTrigger = true; (the simplest and messiest solution, hence why it's commented out)
droppable = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "Drop Platform")
{
//GetComponent<CapsuleCollider2D>().isTrigger = false;
droppable = false;
}
}
Your answer
Follow this Question
Related Questions
How can i store all colliders of colliders which collide with a prefab? 1 Answer
Collider2D of game object does not work, unless I duplicate the game object. 1 Answer
2DCollider Issues 1 Answer
Trying to collide in grid like movement 1 Answer
How to get position of tile on Tilemap Collider 2D? 0 Answers