Home > Net >  Unity RaycastHit2D with something specific
Unity RaycastHit2D with something specific

Time:05-06

I have a laser. its goes on forever. But when the laser touches ANYTHING like (wall, player, box, trigger colliders, etc...) it stops there. So it basically doesnt go through colliders.

But I dont want that. I want the laser to ONLY stop if the RaycastHit2D hits a wall. Is there a way to do that? thanks in advance :D

Here's the code:

private LineRenderer lineRenderer;
public Transform LaserHit;
public Transform LaserSpawn;

void Start()
{
    lineRenderer = GetComponent<LineRenderer>();
    lineRenderer.useWorldSpace = true;
}

void Update()
{
    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
    LaserHit.position = hit.point;
    lineRenderer.SetPosition(0, transform.position);
    lineRenderer.SetPosition(1, LaserHit.position);
}

CodePudding user response:

Create a Layer for walls by going to any GameObject and, under its name, expand the "Layer" box then go to "Add Layer" and name it "Walls" or something.

enter image description here

Then go to your walls and set the Layer for each wall to the "Walls" layer you created.

enter image description here

Then when you raycast, use the Walls layer as the layer mask:

void Update()
{
    int layerMask = LayerMask.GetMask("Walls");
    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up, Mathf.Infinity, layerMask);
    LaserHit.position = hit.point;
    lineRenderer.SetPosition(0, transform.position);
    lineRenderer.SetPosition(1, LaserHit.position);
}

CodePudding user response:

Make it simple and controllable, with only layerMask.value:

public LayerMask laserHitLayer;

public void RayCast()
{
    var Hit = Physics2D.Raycast(transform.position, transform.up, 2f, laserHitLayer.value);
    
    if (!Hit) return;
    
    // do something when on hit
}

You can easily select and change the desired layer in the inspector.

Layer Mask

  • Related