Raycast2D with objects of same type on same LayerMask
Hi there.
I am working on a 2D game that uses Raycasting without Rigidbodies, which is a requirement. I have only two objects: actor (being on the layer "actor") and wall (being on the "solid" layer).
In a level there can be a custom number of actors which should not interact between themselves (aka. if a moving actor hits another actor, the movement should stop). I am using BoxCastAll to check for any hits. However, because the actors are all on the same layer, the code returns also the object that does the raycast. I also tried turning the Queries Start In Colliders
option off, but then the hits return an empty array, and the objects still enter each other.
I am using this code to check whether the actor can move:
public bool CanMoveTo(Vector2 motion, ref RaycastHit2D[] hits, LayerMask layerMask)
{
hits = Physics2D.BoxCastAll(transform.position,Vector2.one*16, 0.0f, motion, motion.magnitude, layerMask);
foreach (RaycastHit2D hit in hits)
if (hit.transform.GetInstanceID() != myTransform.GetInstanceID())
return false;
return true;
}
So my question is: how can I achieve the desired results by using the code above or by changing it. Am I doing something wrong? Thanks in advance.
Note:
I moved from MonoGame to Unity and thought that the transition would be easier. However, it ended up more complicated than I thought. So tell me if I am doing something wrong or am missing something.
Your answer
Follow this Question
Related Questions
Rigidbody blocking raycasts 2D 0 Answers
Ignore Raycast not working properly? 0 Answers
I can't get Raycasting in 2D to work, what am I missing? 1 Answer
Select from multiple character to move 0 Answers
2D raycast not working 0 Answers