How to know what side of platform the player touches?
So I've done research on this and there's a couple ways to do this: Through normal collision using the contact point and collider's center, then there's raycasting.
I've tried the collision method but it doesn't account for the intersection of the platform tiles.
To be specific, each platform is a prefab that is painted in scene using tilemap prefab brush. Each prefab has a BoxCollider2D attached. The collisions trigger as normal except if you're directly at where the two platforms meet, you will be seen as being to the side of both platforms, even if you're on top or below them.
What I'm trying to do is to set the tag of the platform either floor, wall, or ceiling, depending on which side the player collides with.
My script (attached to platforms):
private void OnCollisionEnter2D (Collision2D otherCollider)
{
Collider2D thisCollider = otherCollider.collider; // This collider
// If collision with player
if (otherCollider.gameObject.tag == "Player")
{
Vector3 contactPoint = otherCollider.contacts[0].point; // Point at which other collider intersects with this collider
Vector3 center = thisCollider.bounds.center; // Center point of this collider to use as reference for where player is in relation to this point
// If player is to side of platform
if (contactPoint.x > center.x || contactPoint.x < center.x)
{
// Set tag
this.tag = "Wall";
}
// Else if player is not to side of platform
else
{
///If player is above platform
if (contactPoint.y < center.y)
{
// Set tag
this.tag = "Floor";
}
// Else if player is below platform
else
{
// Set tag
this.tag = "Ceiling";
}
}
}
}
Any help would be greatly appreciated!
Your answer
Follow this Question
Related Questions
How to access the coordinate x y after normalized it by another variable? 0 Answers
Bounds and extents of a tilemap collider across differing y axes, Tilemap collider bounds 0 Answers
Adding prefab object on collision to a another script 0 Answers
Constant Collision 1 Answer
Problems with raycasting 2D. Probelmas com raycasting 2D. 0 Answers