Rigidbody2D.Cast() against mutiple colliders with a single Rigidbody2D
TL;DR: RigidBody2D.Cast() returns only one hit result per Rigidbody2D. Is there a way around it?
So I followed this tutorial to create a 2D character controller. Basically it uses RigidBody2D.Cast() to check for the obstacles. I implemented it in a slightly different way:
private readonly RaycastHit2D[] hits = new RaycastHit2D[16];
private List<RaycastHit2D> hitList = new List<RaycastHit2D>(16);
private Vector2 castDir = Vector2.zero;
[SerializeField]
private Rigidbody2D rigid;
public Rigidbody2D Rigid
{
get => rigid;
private set => rigid = value;
}
public float CheckHorizontal(float dist)
{
float dir = Mathf.Sign(dist);
float abs = Mathf.Abs(dist);
castDir.y = 0;
castDir.x = dir;
hitList.Clear();
for (int i = 0; i < Rigid.Cast(castDir, horizontalMask, hits, abs); i++)
hitList.Add(hits[i]);
for (int i = 0; i < hitList.Count; i++)
{
if (abs > hitList[i].distance && hitList[i].normal.x * dir < 0)
abs = hitList[i].distance;
}
return abs * dir;
}
I "White box'd" a level and worked as expected. Then I used 2D tile palette tools to create a level with Composite Colliders.
In this case, when the character is grounded, the Cast() method does not work. While the box collider on my character is detecting all of the collisions, Cast() only detects one single collision, with the ground.
I did a couple more tests and as far as I can tell, the Cast() method detects only one collision per Rigidbody2D.
So my question is, is there an alternative to the Cast() method similar to RaycastAll or is there any other quick solution besides using raycasts?
I also have the same problem. If you have solved this problem, please share your solution with me. Thank you!
I did solve the issue but I don't remember how exactly. I think I just did two separate casts. One for vertical displacement and one for horizontal.
Your answer
Follow this Question
Related Questions
Is there an easy way to make a RigidBody2D collide with only one other RigidBody2D? 1 Answer
Rigidbody2D and non-trigger child colliders! 2 Answers
RigidBody becomes awake without a collision 1 Answer
How to know when the player object falls between tiles in 2D game to take decesion of gameover 1 Answer
Unable to stop animation upon collision (2d, animation, rigidbody) 0 Answers