I want to allow players in my game to activate a moving platform by standing on top of it. This means that the player can only activate the platform by landing on it from above and eventually colliding with the platform. In simpler terms, only the feet of the player should be touching the top of the platform in order for it to activate; any other body part of the player can’t activate the platform. This platform uses a Platform Effector 2D set to 170 degrees facing up, which lets the player go through the platform when coming from below, but still collide with it when coming from above.
The player has the following components in the inspector
- Transform
- Sprite Renderer
- RigidBody2D
- BoxCollider2D
- A script for movement
The platform has the following components in the inspector
- Transform
- Sprite Renderer
- Box Collider 2D
- Platform Effector 2D
- A script for movement
The player moves using the physics engine, and the platform moves using transform.translate.
In this example, the player (the white block) should be activating the red platform, as his feet are touching the top of the platform.
In this example, the player should NOT be activating the red platform, as his feet aren’t on top of the platform and he isn’t standing on it.
I first tried to solve this using colliders and OnCollisionEnter2D, but the problem is when the player jumps from below, the platform activates too early since the player’s collider includes his head, which collides/activates the platform before the entire player’s body gets over the platform and lands.
My second attempt to solve this was to check if the player’s velocity is currently zero or below, to indicate that the player must be from a falling/standing position, but then the platform will still activate if the peak of the player jump just barely has the player’s head enter the platform’s collider. This is because the player’s velocity eventually hits zero at the peak of the jump before going down, and the collider still uses the player’s head.
My third attempt was to use Physics2D.Raycast, and placing the Raycast on the player’s feet. This almost worked, but there is still a problem. If the platform is too vertically-thick such that the player’s collider isn’t on top of the platform yet, and the raycast along his is detecting the platform, then the platform would activate before the player has landed on his feet yet. (Example: https://imgur.com/a/Ng3Ptfv)
At this point, I’m going to be messing with tedious adjustments so that my code works dependently on the size of the platforms / the location of the Raycast. I’m considering calculating the bounds of the colliders of the player and also the platform, but isn’t there a more convenient way? Perhaps there is something in the library or an idea I haven’t come up with?
Thank you.