'PolygonCollider2D.Cast() does not detect TilemapCollider2D
I'm trying to stop the character (PolygonCollider2D) from moving through a wall (TilemapCollider2D).
1 var hitResults = new RaycastHit2D[10];
2 var hitX = collider.Cast(new Vector2(desiredX, 0), bodyFilter, hitResults);
3 //var test = new Collider2D[10];
4 //hitX = collider.OverlapCollider(bodyFilter, test);
5 if (hitX == 0)
6 {
7 transform.Translate(desiredX, 0, 0);
8 }
Why does the character not stop moving horizontally when I run the code like this? I proved the character can collide with the wall because it does stop moving horizontally when I uncomment the two lines (3&4).
Solution 1:[1]
According to the Unity documentation, Collider2D.Cast only works if the gameobject has a RigidBody2D. I do not want to use RigidBody2D because i'm not using the physics in my game.
I ended up adding a CapsuleCollider2D to the gameobject and doing the cast with the Physics2D.CapsuleCast method:
var capsuleCollider = GetComponentInChildren<CapsuleCollider2D>();
var hitX = Physics2D.CapsuleCast(transform.position, capsuleCollider.size, capsuleCollider.direction, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(desiredX), wallFilter.layerMask);
if (hitX.collider == null)
{
transform.Translate(desiredX, 0, 0);
}
In my opinion, this is a workaround. There must be a way to cast the PolygonCollider2D.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Janneman96 |
