Moving Platforms pass through other moving platforms and tilemaps

I am working on a small 2D platformer.

I have a GameObject called Platform which has a box collider and a Kinematic rigid body. Attached to it is this script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
public Collider2D platformCollider;
public Rigidbody2D rb;
public int movingRight=1;

void Start(){
rb.velocity = new Vector2(1.5f * movingRight,0f);
}

void Update()
{
Physics2D.queriesStartInColliders = false;
int mask = 1<<9 | 1<<8;

RaycastHit2D hitrightinfo = Physics2D.Raycast(
new Vector3(platformCollider.bounds.max.x, transform.position.y, 0f), 
Vector2.right, 
100,
mask);

RaycastHit2D hitleftinfo = Physics2D.Raycast(
new Vector3(platformCollider.bounds.min.x, transform.position.y, 0f), 
Vector2.left, 
100, 
mask);

if (hitrightinfo && hitrightinfo.distance<=0.1){
movingRight=-1;
rb.velocity = new Vector2(2f * movingRight,0f);

}else if (hitleftinfo && hitleftinfo.distance<=0.1){
movingRight=1;
rb.velocity = new Vector2(2f * movingRight,0f);
}
} 
}

Which casts two rays (one to left and one to right) which switch the Platforms moving direction when it gets too close to any layer 8 or 9 colliders.

I am having an issue where the Platforms move through other Platforms/tilemap even though they are in layers 8 and 9.

Any ideas why would this happen?

I’m taking a stab in the dark here, but i think that your mask is ignoring layer 8/9 platforms

1 Like

No, it works sometimes and sometimes not.

Why?

https://docs.unity3d.com/2019.3/Documentation/Manual/class-Rigidbody2D.html

When using dynamic rigid body it appeared that the platform was applying force to the player when it moves. So the player would get stuck on the “jumping up” and “falling down” animation loop as long as the layer is on the platform.

Are you sure your platform is on the layers you mention and the other tilemaps and objects it collides with are not?

As I said before, it sometimes works and sometimes not. That means the layers are correct.