I have made a LineRenderer
and I added an EdgeCollider2D
to it.
Now I am trying to detect all GameObjects
below my LineRenderer
.
The objects below have Colliders as well.
LineRenderer
starts with first mouse position and ends with last mouse positionLineRenderer
has anEdgeCollider2D
- I need to get value from all objects which are under
LineRenderer
- Project is in 2D
What I tried:
Use Raycast,but using raycast I am getting values from object around too.
And i want only to get values of Gameobjects under Linerenderer not values from All gameobjects touched by mouse
Or if it is Possible to get gameobjects between 2 positions *So basicaly i need to get values from 10 of 100 objects,which are all together.F.E i have 100 mushrooms placed together,and every mushroom have its int value which is different. So moving my mouse around i need to select only this 10 mushrooms and take its value.
Here is my code so far
RaycastHit2D[] rays = Physics2D.RaycastAll(mousePos, lr.transform.forward);
Debug.DrawRay(new Vector3(startMousePosition.x, startMousePosition.y, 0), Vector3.up, Color.red, 5);
for (int i = 0; i < rays.Length; i )
{
RaycastHit2D ray = rays[i];
if (isTOuched)
{
if (ray.collider.gameObject.tag == "Player")
{
if (objektiOdRaycast.Contains(ray.collider.gameObject) == false)
{
objektiOdRaycast.Add(ray.collider.gameObject);
for (int t = 0; t < objektiOdRaycast.Count; t )
{
tekst = objektiOdRaycast[t].GetComponent < GridSquare().tekst;
}
words.tekstSlova.text = tekst;
}
}
}
}
CodePudding user response:
The problem with a Raycast
is: It only checks one single ray direction. That makes no sense in your use case.
You probably want to use Physics2D.OverlapCollider
Gets a list of all Colliders that overlap the given Collider.
and do e.g.
// Reference via the Inspector
public LineRenderer theLine;
// configure via the Inspector
public ContactFilter2D filter;
private Collider2D lineCollider;
private readonly List<Collider2D> overlaps = new List<Collider2D>();
private readonly HashSet<Collider2D> alreadySeen = new HashSet<Collider2D>();
private void Awake()
{
// as fallback assume same GameObject
if(!theLine) theLine = GetComponent<LineRenderer>();
lineCollider = theLine.GetComponent<Collider2D>();
}
public void GetOverlappingObjects()
{
var amount = Physics2D.OverlapCollider(lineCollider, filter, overlaps);
for(var i = 0; i < amount; i )
{
var overlap = overlaps[i];
if(alreadySeen.Contains(overlap)) continue;
alreadySeen.Add(overlap);
var overlapObject = overlap.gameObject;
// These checks are actually kind of redundant
// the second heck for the component should already be enough
// instead of the tag you could rather use a Layer and configure the filter accordingly
if (!overlapObject.CompareTag("Player")) continue;
if (!overlapObject.TryGetComponent<GridSquare>(out var gridSquare)) continue;
words.tekstSlova.text = gridSquare.tekst;
}
}