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?